pg_dump.c 157.3 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * pg_dump.c
4
 *	  pg_dump is a utility for dumping out a postgres database
B
Bruce Momjian 已提交
5
 *	  into a script file.
6
 *
B
Bruce Momjian 已提交
7
 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
8
 * Portions Copyright (c) 1994, Regents of the University of California
9
 *
10 11 12 13 14 15
 *	pg_dump will read the system catalogs in a database and
 *	dump out a script that reproduces
 *	the schema of the database in terms of
 *		  user-defined types
 *		  user-defined functions
 *		  tables
16
 *		  indexes
17 18
 *		  aggregates
 *		  operators
19
 *		  privileges
20
 *
21
 * the output script is SQL that is understood by PostgreSQL
22 23 24
 *
 *
 * IDENTIFICATION
25
 *	  $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_dump.c,v 1.268 2002/07/02 05:49:51 momjian Exp $
26
 *
27
 *-------------------------------------------------------------------------
28 29
 */

30 31 32 33 34 35 36
/*
 * Although this is not a backend module, we must include postgres.h anyway
 * so that we can include a bunch of backend include files.  pg_dump has
 * never pretended to be very independent of the backend anyhow ...
 */
#include "postgres.h"

37
#include <unistd.h>				/* for getopt() */
38
#include <ctype.h>
39 40 41
#ifdef ENABLE_NLS
#include <locale.h>
#endif
42 43 44 45 46 47 48
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif

49 50 51 52
#ifndef HAVE_STRDUP
#include "strdup.h"
#endif

53
#include "access/attnum.h"
54
#include "access/htup.h"
55
#include "catalog/pg_class.h"
56
#include "catalog/pg_proc.h"
V
Vadim B. Mikheev 已提交
57
#include "catalog/pg_trigger.h"
58
#include "catalog/pg_type.h"
59

60
#include "libpq-fe.h"
61
#include "libpq/libpq-fs.h"
62 63

#include "pg_dump.h"
B
Bruce Momjian 已提交
64
#include "pg_backup.h"
65
#include "pg_backup_archiver.h"
66

67

B
Bruce Momjian 已提交
68 69
typedef enum _formatLiteralOptions
{
70 71
	CONV_ALL = 0,
	PASS_LFTAB = 3				/* NOTE: 1 and 2 are reserved in case we
B
Bruce Momjian 已提交
72 73 74 75
								 * want to make a mask. */
	/* We could make this a bit mask for control chars, but I don't */
	/* see any value in making it more complex...the current code */
	/* only checks for 'opts == CONV_ALL' anyway. */
76 77
} formatLiteralOptions;

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
typedef struct _dumpContext
{
	TableInfo  *tblinfo;
	int			tblidx;
	bool		oids;
} DumpContext;

static void help(const char *progname);
static int	parse_version(const char *versionString);
static NamespaceInfo *findNamespace(const char *nsoid, const char *objoid);
static void dumpClasses(const TableInfo *tblinfo, const int numTables,
						Archive *fout, const bool oids);
static void dumpComment(Archive *fout, const char *target,
						const char *namespace, const char *owner,
						const char *oid, const char *classname, int subid,
						const char *((*deps)[]));
static void dumpOneBaseType(Archive *fout, TypeInfo *tinfo,
							FuncInfo *g_finfo, int numFuncs,
							TypeInfo *g_tinfo, int numTypes);
97
static void dumpOneDomain(Archive *fout, TypeInfo *tinfo);
98 99 100 101
static void dumpOneTable(Archive *fout, TableInfo *tbinfo,
						 TableInfo *g_tblinfo);
static void dumpOneSequence(Archive *fout, TableInfo *tbinfo,
							const bool schemaOnly, const bool dataOnly);
102 103 104 105 106 107 108 109

static void dumpTableACL(Archive *fout, TableInfo *tbinfo);
static void dumpFuncACL(Archive *fout, FuncInfo *finfo);
static void dumpAggACL(Archive *fout, AggInfo *finfo);
static void dumpACL(Archive *fout, const char *type, const char *name,
					const char *nspname, const char *usename,
					const char *acl, const char *objoid);

110 111 112 113
static void dumpTriggers(Archive *fout, TableInfo *tblinfo, int numTables);
static void dumpRules(Archive *fout, TableInfo *tblinfo, int numTables);
static void formatStringLiteral(PQExpBuffer buf, const char *str,
								const formatLiteralOptions opts);
114
static char *format_function_signature(FuncInfo *finfo);
115 116 117 118 119 120 121
static void dumpOneFunc(Archive *fout, FuncInfo *finfo);
static void dumpOneOpr(Archive *fout, OprInfo *oprinfo,
					   OprInfo *g_oprinfo, int numOperators);
static const char *convertRegProcReference(const char *proc);
static const char *convertOperatorReference(const char *opr,
						OprInfo *g_oprinfo, int numOperators);
static void dumpOneAgg(Archive *fout, AggInfo *agginfo);
122 123
static Oid	findLastBuiltinOid_V71(const char *);
static Oid	findLastBuiltinOid_V70(void);
B
Bruce Momjian 已提交
124
static void setMaxOid(Archive *fout);
125 126 127 128
static void selectSourceSchema(const char *schemaName);
static char *getFormattedTypeName(const char *oid, OidOptions opts);
static char *myFormatType(const char *typname, int32 typmod);
static const char *fmtQualifiedId(const char *schema, const char *id);
129

130
static void AddAcl(char *aclbuf, const char *keyword);
131
static char *GetPrivileges(Archive *AH, const char *s, const char *type);
V
Vadim B. Mikheev 已提交
132

B
Bruce Momjian 已提交
133 134
static int	dumpBlobs(Archive *AH, char *, void *);
static int	dumpDatabase(Archive *AH);
135
static const char *getAttrName(int attrnum, TableInfo *tblInfo);
136

B
Bruce Momjian 已提交
137
extern char *optarg;
138
extern int	optind,
B
Bruce Momjian 已提交
139
			opterr;
140 141

/* global decls */
142
bool		g_verbose;			/* User wants verbose narration of our
B
Bruce Momjian 已提交
143
								 * activities. */
B
Bruce Momjian 已提交
144
Archive    *g_fout;				/* the script file */
B
Bruce Momjian 已提交
145 146
PGconn	   *g_conn;				/* the database connection */

147
/* various user-settable parameters */
B
Bruce Momjian 已提交
148
bool		force_quotes;		/* User wants to suppress double-quotes */
149 150 151 152
bool		dumpData;			/* dump data using proper insert strings */
bool		attrNames;			/* put attr names into insert strings */
bool		schemaOnly;
bool		dataOnly;
153
bool		aclsSkip;
154

155 156 157 158 159
/* obsolete as of 7.3: */
static Oid	g_last_builtin_oid; /* value of the last builtin oid */

static char *selectTablename = NULL;	/* name of a single table to dump */

B
Bruce Momjian 已提交
160
char		g_opaque_type[10];	/* name for the opaque type */
161 162

/* placeholders for the delimiters for comments */
163 164
char		g_comment_start[10];
char		g_comment_end[10];
165

166 167 168
/* these are to avoid passing around info for findNamespace() */
static NamespaceInfo *g_namespaces;
static int	g_numNamespaces;
169

170 171 172

int
main(int argc, char **argv)
B
Bruce Momjian 已提交
173
{
174 175 176 177 178 179 180 181
	int			c;
	const char *filename = NULL;
	const char *format = "p";
	const char *dbname = NULL;
	const char *pghost = NULL;
	const char *pgport = NULL;
	const char *username = NULL;
	bool		oids = false;
B
Bruce Momjian 已提交
182
	TableInfo  *tblinfo;
183 184 185 186 187 188 189 190 191 192 193 194 195
	int			numTables;
	bool		force_password = false;
	int			compressLevel = -1;
	bool		ignore_version = false;
	int			plainText = 0;
	int			outputClean = 0;
	int			outputCreate = 0;
	int			outputBlobs = 0;
	int			outputNoOwner = 0;
	int			outputNoReconnect = 0;
	static int	use_setsessauth = 0;
	static int	disable_triggers = 0;
	char	   *outputSuperuser = NULL;
B
Bruce Momjian 已提交
196

197
	RestoreOptions *ropt;
B
Hi,  
Bruce Momjian 已提交
198 199

#ifdef HAVE_GETOPT_LONG
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
	static struct option long_options[] = {
		{"data-only", no_argument, NULL, 'a'},
		{"blobs", no_argument, NULL, 'b'},
		{"clean", no_argument, NULL, 'c'},
		{"create", no_argument, NULL, 'C'},
		{"file", required_argument, NULL, 'f'},
		{"format", required_argument, NULL, 'F'},
		{"inserts", no_argument, NULL, 'd'},
		{"attribute-inserts", no_argument, NULL, 'D'},
		{"column-inserts", no_argument, NULL, 'D'},
		{"host", required_argument, NULL, 'h'},
		{"ignore-version", no_argument, NULL, 'i'},
		{"no-reconnect", no_argument, NULL, 'R'},
		{"no-quotes", no_argument, NULL, 'n'},
		{"quotes", no_argument, NULL, 'N'},
		{"oids", no_argument, NULL, 'o'},
		{"no-owner", no_argument, NULL, 'O'},
		{"port", required_argument, NULL, 'p'},
		{"schema-only", no_argument, NULL, 's'},
		{"superuser", required_argument, NULL, 'S'},
		{"table", required_argument, NULL, 't'},
		{"password", no_argument, NULL, 'W'},
		{"username", required_argument, NULL, 'U'},
		{"verbose", no_argument, NULL, 'v'},
		{"no-privileges", no_argument, NULL, 'x'},
		{"no-acl", no_argument, NULL, 'x'},
		{"compress", required_argument, NULL, 'Z'},
		{"help", no_argument, NULL, '?'},
		{"version", no_argument, NULL, 'V'},
229

230 231 232 233 234 235
		/*
		 * the following options don't have an equivalent short option
		 * letter, but are available as '-X long-name'
		 */
		{"use-set-session-authorization", no_argument, &use_setsessauth, 1},
		{"disable-triggers", no_argument, &disable_triggers, 1},
236

237 238 239 240
		{NULL, 0, NULL, 0}
	};
	int			optindex;
#endif
241

242 243 244 245 246
#ifdef ENABLE_NLS
	setlocale(LC_ALL, "");
	bindtextdomain("pg_dump", LOCALEDIR);
	textdomain("pg_dump");
#endif
247

248 249
	g_verbose = false;
	force_quotes = true;
250

251 252 253
	strcpy(g_comment_start, "-- ");
	g_comment_end[0] = '\0';
	strcpy(g_opaque_type, "opaque");
254

255
	dataOnly = schemaOnly = dumpData = attrNames = false;
256

257 258
	if (!strrchr(argv[0], '/'))
		progname = argv[0];
259
	else
260
		progname = strrchr(argv[0], '/') + 1;
261

262 263
	/* Set default options based on progname */
	if (strcmp(progname, "pg_backup") == 0)
264
	{
265 266
		format = "c";
		outputBlobs = true;
267
	}
268 269

	if (argc > 1)
270
	{
271
		if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
272
		{
273 274
			help(progname);
			exit(0);
275
		}
276
		if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
277
		{
278 279
			puts("pg_dump (PostgreSQL) " PG_VERSION);
			exit(0);
280 281
		}
	}
282

283 284 285 286 287
#ifdef HAVE_GETOPT_LONG
	while ((c = getopt_long(argc, argv, "abcCdDf:F:h:inNoOp:RsS:t:uU:vWxX:zZ:V?", long_options, &optindex)) != -1)
#else
	while ((c = getopt(argc, argv, "abcCdDf:F:h:inNoOp:RsS:t:uU:vWxX:zZ:V?-")) != -1)
#endif
288

289 290 291 292 293 294
	{
		switch (c)
		{
			case 'a':			/* Dump data only */
				dataOnly = true;
				break;
B
Bruce Momjian 已提交
295

296 297 298
			case 'b':			/* Dump blobs */
				outputBlobs = true;
				break;
299

300 301 302 303
			case 'c':			/* clean (i.e., drop) schema prior to
								 * create */
				outputClean = 1;
				break;
304

305
			case 'C':			/* Create DB */
306

307 308
				outputCreate = 1;
				break;
309

310 311 312
			case 'd':			/* dump data as proper insert strings */
				dumpData = true;
				break;
313

314 315 316 317 318
			case 'D':			/* dump data as proper insert strings with
								 * attr names */
				dumpData = true;
				attrNames = true;
				break;
319

320 321 322
			case 'f':
				filename = optarg;
				break;
323

324 325 326
			case 'F':
				format = optarg;
				break;
327

328 329 330
			case 'h':			/* server host */
				pghost = optarg;
				break;
331

332 333 334
			case 'i':			/* ignore database version mismatch */
				ignore_version = true;
				break;
335

336 337 338 339
			case 'n':			/* Do not force double-quotes on
								 * identifiers */
				force_quotes = false;
				break;
340

341 342 343
			case 'N':			/* Force double-quotes on identifiers */
				force_quotes = true;
				break;
344

345 346 347
			case 'o':			/* Dump oids */
				oids = true;
				break;
B
Bruce Momjian 已提交
348

349

350 351 352
			case 'O':			/* Don't reconnect to match owner */
				outputNoOwner = 1;
				break;
353

354 355 356
			case 'p':			/* server port */
				pgport = optarg;
				break;
357

358 359 360
			case 'R':			/* No reconnect */
				outputNoReconnect = 1;
				break;
361

362 363 364
			case 's':			/* dump schema only */
				schemaOnly = true;
				break;
365

366 367 368 369
			case 'S':			/* Username for superuser in plain text
								 * output */
				outputSuperuser = strdup(optarg);
				break;
B
Bruce Momjian 已提交
370

371 372 373
			case 't':			/* Dump data for this table only */
				{
					int			i;
374

375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 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
					selectTablename = strdup(optarg);

					/*
					 * quoted string? Then strip quotes and preserve
					 * case...
					 */
					if (selectTablename[0] == '"')
					{
						char	*endptr;

						endptr = selectTablename + strlen(selectTablename) - 1;
						if (*endptr == '"')
							*endptr = '\0';
						strcpy(selectTablename, &selectTablename[1]);
					}
					else
					{
						/* otherwise, convert table name to lowercase... */
						for (i = 0; selectTablename[i]; i++)
							if (isupper((unsigned char) selectTablename[i]))
								selectTablename[i] = tolower((unsigned char) selectTablename[i]);

						/*
						 * '*' is a special case meaning ALL tables, but
						 * only if unquoted
						 */
						if (strcmp(selectTablename, "*") == 0)
							selectTablename[0] = '\0';
					}
				}
				break;

			case 'u':
				force_password = true;
				username = simple_prompt("User name: ", 100, true);
				break;

			case 'U':
				username = optarg;
				break;

			case 'v':			/* verbose */
				g_verbose = true;
				break;

			case 'W':
				force_password = true;
				break;

			case 'x':			/* skip ACL dump */
				aclsSkip = true;
				break;

				/*
				 * Option letters were getting scarce, so I invented this
				 * new scheme: '-X feature' turns on some feature. Compare
				 * to the -f option in GCC.  You should also add an
				 * equivalent GNU-style option --feature.  Features that
				 * require arguments should use '-X feature=foo'.
				 */
			case 'X':
				if (strcmp(optarg, "use-set-session-authorization") == 0)
					use_setsessauth = 1;
				else if (strcmp(optarg, "disable-triggers") == 0)
					disable_triggers = 1;
				else
				{
					fprintf(stderr,
							gettext("%s: invalid -X option -- %s\n"),
							progname, optarg);
					fprintf(stderr, gettext("Try '%s --help' for more information.\n"), progname);
					exit(1);
				}
				break;
			case 'Z':			/* Compression Level */
				compressLevel = atoi(optarg);
				break;
B
Bruce Momjian 已提交
452

453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
#ifndef HAVE_GETOPT_LONG
			case '-':
				fprintf(stderr,
						gettext("%s was compiled without support for long options.\n"
						 "Use --help for help on invocation options.\n"),
						progname);
				exit(1);
				break;
#else
				/* This covers the long options equivalent to -X xxx. */
			case 0:
				break;
#endif
			default:
				fprintf(stderr, gettext("Try '%s --help' for more information.\n"), progname);
				exit(1);
469
		}
470
	}
471

472 473 474 475 476 477 478 479
	if (optind < (argc - 1))
	{
		fprintf(stderr,
			gettext("%s: too many command line options (first is '%s')\n"
					"Try '%s --help' for more information.\n"),
				progname, argv[optind + 1], progname);
		exit(1);
	}
480

481 482 483 484 485 486 487 488 489 490
	/* Get the target database name */
	if (optind < argc)
		dbname = argv[optind];
	else
		dbname = getenv("PGDATABASE");
	if (!dbname)
	{
		write_msg(NULL, "no database name specified\n");
		exit(1);
	}
491

492 493 494 495 496
	if (dataOnly && schemaOnly)
	{
		write_msg(NULL, "The options \"schema only\" (-s) and \"data only\" (-a) cannot be used together.\n");
		exit(1);
	}
497

498 499 500 501 502 503
	if (outputBlobs && selectTablename != NULL && strlen(selectTablename) > 0)
	{
		write_msg(NULL, "Large object output is not supported for a single table.\n");
		write_msg(NULL, "Use all tables or a full dump instead.\n");
		exit(1);
	}
504

505
	if (dumpData == true && oids == true)
506
	{
507 508
		write_msg(NULL, "INSERT (-d, -D) and OID (-o) options cannot be used together.\n");
		write_msg(NULL, "(The INSERT command cannot set oids.)\n");
509 510 511
		exit(1);
	}

512 513 514 515 516 517
	if (outputBlobs == true && (format[0] == 'p' || format[0] == 'P'))
	{
		write_msg(NULL, "large object output is not supported for plain text dump files.\n");
		write_msg(NULL, "(Use a different output format.)\n");
		exit(1);
	}
518

519 520 521
	/* open the output file */
	switch (format[0])
	{
522

523 524 525 526
		case 'c':
		case 'C':
			g_fout = CreateArchive(filename, archCustom, compressLevel);
			break;
527

528 529 530 531
		case 'f':
		case 'F':
			g_fout = CreateArchive(filename, archFiles, compressLevel);
			break;
532

533 534 535 536 537
		case 'p':
		case 'P':
			plainText = 1;
			g_fout = CreateArchive(filename, archNull, 0);
			break;
538

539 540 541 542
		case 't':
		case 'T':
			g_fout = CreateArchive(filename, archTar, compressLevel);
			break;
543

544 545 546 547
		default:
			write_msg(NULL, "invalid output format '%s' specified\n", format);
			exit(1);
	}
548

549 550 551 552 553
	if (g_fout == NULL)
	{
		write_msg(NULL, "could not open output file %s for writing\n", filename);
		exit(1);
	}
B
Hi,  
Bruce Momjian 已提交
554

555 556
	/* Let the archiver know how noisy to be */
	g_fout->verbose = g_verbose;
557

558 559 560 561 562 563 564
	/*
	 * Open the database using the Archiver, so it knows about it. Errors
	 * mean death.
	 */
	g_fout->minRemoteVersion = 70000;	/* we can handle back to 7.0 */
	g_fout->maxRemoteVersion = parse_version(PG_VERSION);
	g_conn = ConnectDatabase(g_fout, dbname, pghost, pgport, username, force_password, ignore_version);
565

566 567 568 569 570
	/*
	 * Start serializable transaction to dump consistent data
	 */
	{
		PGresult   *res;
571

572 573 574 575
		res = PQexec(g_conn, "begin");
		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
			exit_horribly(g_fout, NULL, "BEGIN command failed: %s",
						  PQerrorMessage(g_conn));
576

577 578 579 580 581
		PQclear(res);
		res = PQexec(g_conn, "set transaction isolation level serializable");
		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
			exit_horribly(g_fout, NULL, "could not set transaction isolation level to serializable: %s",
						  PQerrorMessage(g_conn));
582

583
		PQclear(res);
584
	}
585

586
	if (g_fout->remoteVersion < 70300)
587
	{
588 589 590 591 592 593
		if (g_fout->remoteVersion >= 70100)
			g_last_builtin_oid = findLastBuiltinOid_V71(dbname);
		else
			g_last_builtin_oid = findLastBuiltinOid_V70();
		if (g_verbose)
			write_msg(NULL, "last built-in oid is %u\n", g_last_builtin_oid);
594 595
	}

596 597 598
	/* Dump the database definition */
	if (!dataOnly)
		dumpDatabase(g_fout);
B
Bruce Momjian 已提交
599

600 601
	if (oids == true)
		setMaxOid(g_fout);
602

603
	tblinfo = dumpSchema(g_fout, &numTables, aclsSkip, schemaOnly, dataOnly);
604

605 606
	if (!schemaOnly)
		dumpClasses(tblinfo, numTables, g_fout, oids);
607

608 609 610
	if (outputBlobs)
		ArchiveEntry(g_fout, "0", "BLOBS", NULL, "",
					 "BLOBS", NULL, "", "", NULL, dumpBlobs, NULL);
611

612 613 614 615 616 617
	if (!dataOnly)				/* dump indexes and triggers at the end
								 * for performance */
	{
		dumpTriggers(g_fout, tblinfo, numTables);
		dumpRules(g_fout, tblinfo, numTables);
	}
618

619 620 621 622 623 624 625 626 627 628 629
	/* Now sort the output nicely */
	SortTocByOID(g_fout);
	MoveToStart(g_fout, "SCHEMA");
	MoveToStart(g_fout, "DATABASE");
	MoveToEnd(g_fout, "TABLE DATA");
	MoveToEnd(g_fout, "BLOBS");
	MoveToEnd(g_fout, "INDEX");
	MoveToEnd(g_fout, "CONSTRAINT");
	MoveToEnd(g_fout, "TRIGGER");
	MoveToEnd(g_fout, "RULE");
	MoveToEnd(g_fout, "SEQUENCE SET");
630

631 632 633 634 635 636
	/*
	 * Moving all comments to end is annoying, but must do it for comments
	 * on stuff we just moved, and we don't seem to have quite enough
	 * dependency structure to get it really right...
	 */
	MoveToEnd(g_fout, "COMMENT");
637

638 639 640 641 642 643 644 645 646 647 648 649
	if (plainText)
	{
		ropt = NewRestoreOptions();
		ropt->filename = (char *) filename;
		ropt->dropSchema = outputClean;
		ropt->aclsSkip = aclsSkip;
		ropt->superuser = outputSuperuser;
		ropt->create = outputCreate;
		ropt->noOwner = outputNoOwner;
		ropt->noReconnect = outputNoReconnect;
		ropt->use_setsessauth = use_setsessauth;
		ropt->disable_triggers = disable_triggers;
650

651 652 653 654
		if (compressLevel == -1)
			ropt->compression = 0;
		else
			ropt->compression = compressLevel;
655

656 657
		ropt->suppressDumpWarnings = true;		/* We've already shown
												 * them */
658

659 660
		RestoreArchive(g_fout, ropt);
	}
661

662
	CloseArchive(g_fout);
663

664 665 666
	PQfinish(g_conn);
	exit(0);
}
667 668


669 670 671 672 673 674 675
static void
help(const char *progname)
{
	printf(gettext("%s dumps a database as a text file or to other formats.\n\n"), progname);
	puts(gettext("Usage:"));
	printf(gettext("  %s [options] dbname\n\n"), progname);
	puts(gettext("Options:"));
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 710 711 712 713 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 740 741 742 743 744 745 746 747 748 749 750 751 752
#ifdef HAVE_GETOPT_LONG
	puts(gettext(
		"  -a, --data-only          dump only the data, not the schema\n"
		"  -b, --blobs              include large objects in dump\n"
		"  -c, --clean              clean (drop) schema prior to create\n"
		"  -C, --create             include commands to create database in dump\n"
		"  -d, --inserts            dump data as INSERT, rather than COPY, commands\n"
		"  -D, --column-inserts     dump data as INSERT commands with column names\n"
		"  -f, --file=FILENAME      output file name\n"
		"  -F, --format {c|t|p}     output file format (custom, tar, plain text)\n"
		"  -h, --host=HOSTNAME      database server host name\n"
		"  -i, --ignore-version     proceed even when server version mismatches\n"
		"                           pg_dump version\n"
		"  -n, --no-quotes          suppress most quotes around identifiers\n"
		"  -N, --quotes             enable most quotes around identifiers\n"
		"  -o, --oids               include oids in dump\n"
		"  -O, --no-owner           do not output \\connect commands in plain\n"
		"                           text format\n"
		"  -p, --port=PORT          database server port number\n"
		"  -R, --no-reconnect       disable ALL reconnections to the database in\n"
		"                           plain text format\n"
		"  -s, --schema-only        dump only the schema, no data\n"
		"  -S, --superuser=NAME     specify the superuser user name to use in\n"
		"                           plain text format\n"
		"  -t, --table=TABLE        dump this table only (* for all)\n"
		"  -U, --username=NAME      connect as specified database user\n"
		"  -v, --verbose            verbose mode\n"
		"  -W, --password           force password prompt (should happen automatically)\n"
		"  -x, --no-privileges      do not dump privileges (grant/revoke)\n"
		"  -X use-set-session-authorization, --use-set-session-authorization\n"
		"                           output SET SESSION AUTHORIZATION commands rather\n"
		"                           than \\connect commands\n"
		"  -X disable-triggers, --disable-triggers\n"
		"                           disable triggers during data-only restore\n"
		"  -Z, --compress {0-9}     compression level for compressed formats\n"
	));
#else
	puts(gettext(
		"  -a                       dump only the data, not the schema\n"
		"  -b                       include large objects in dump\n"
		"  -c                       clean (drop) schema prior to create\n"
		"  -C                       include commands to create database in dump\n"
		"  -d                       dump data as INSERT, rather than COPY, commands\n"
		"  -D                       dump data as INSERT commands with column names\n"
		"  -f FILENAME              output file name\n"
		"  -F {c|t|p}               output file format (custom, tar, plain text)\n"
		"  -h HOSTNAME              database server host name\n"
		"  -i                       proceed even when server version mismatches\n"
		"                           pg_dump version\n"
		"  -n                       suppress most quotes around identifiers\n"
		"  -N                       enable most quotes around identifiers\n"
		"  -o                       include oids in dump\n"
		"  -O                       do not output \\connect commands in plain\n"
		"                           text format\n"
		"  -p PORT                  database server port number\n"
		"  -R                       disable ALL reconnections to the database in\n"
		"                           plain text format\n"
		"  -s                       dump only the schema, no data\n"
		"  -S NAME                  specify the superuser user name to use in\n"
		"                           plain text format\n"
		"  -t TABLE                 dump this table only (* for all)\n"
		"  -U NAME                  connect as specified database user\n"
		"  -v                       verbose mode\n"
		"  -W                       force password prompt (should happen automatically)\n"
		"  -x                       do not dump privileges (grant/revoke)\n"
		"  -X use-set-session-authorization\n"
		"                           output SET SESSION AUTHORIZATION commands rather\n"
		"                           than \\connect commands\n"
		"  -X disable-triggers      disable triggers during data-only restore\n"
		"  -Z {0-9}                 compression level for compressed formats\n"
	));
#endif
	puts(gettext("If no database name is not supplied, then the PGDATABASE environment\n"
				 "variable value is used.\n\n"
				 "Report bugs to <pgsql-bugs@postgresql.org>."));
}
753

754 755 756 757 758 759 760
static int
parse_version(const char *versionString)
{
	int			cnt;
	int			vmaj,
				vmin,
				vrev;
761

762
	cnt = sscanf(versionString, "%d.%d.%d", &vmaj, &vmin, &vrev);
763

764 765 766 767 768
	if (cnt < 2)
	{
		write_msg(NULL, "unable to parse version string \"%s\"\n", versionString);
		exit(1);
	}
B
Bruce Momjian 已提交
769

770 771
	if (cnt == 2)
		vrev = 0;
772

773 774
	return (100 * vmaj + vmin) * 100 + vrev;
}
775

776 777 778 779 780 781 782 783
void
exit_nicely(void)
{
	PQfinish(g_conn);
	if (g_verbose)
		write_msg(NULL, "*** aborted because of error\n");
	exit(1);
}
784

785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
/*
 * selectDumpableNamespace: policy-setting subroutine
 *		Mark a namespace as to be dumped or not
 */
static void
selectDumpableNamespace(NamespaceInfo *nsinfo)
{
	/*
	 * If a specific table is being dumped, do not dump any complete
	 * namespaces.  Otherwise, dump all non-system namespaces.
	 */
	if (selectTablename != NULL)
		nsinfo->dump = false;
	else if (strncmp(nsinfo->nspname, "pg_", 3) == 0)
		nsinfo->dump = false;
	else
		nsinfo->dump = true;
}
803

804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
/*
 * selectDumpableTable: policy-setting subroutine
 *		Mark a table as to be dumped or not
 */
static void
selectDumpableTable(TableInfo *tbinfo)
{
	/*
	 * Always dump if dumping parent namespace; else, if a particular
	 * tablename has been specified, dump matching table name; else,
	 * do not dump.
	 */
	if (tbinfo->relnamespace->dump)
		tbinfo->dump = true;
	else if (selectTablename != NULL)
		tbinfo->dump = (strcmp(tbinfo->relname, selectTablename) == 0);
	else
		tbinfo->dump = false;
}
823

824 825 826 827 828
/*
 *	Dump a table's contents for loading using the COPY command
 *	- this routine is called by the Archiver when it wants the table
 *	  to be dumped.
 */
829

830
#define COPYBUFSIZ		8192
831

832 833 834 835 836 837 838 839 840 841 842 843 844
static int
dumpClasses_nodumpData(Archive *fout, char *oid, void *dctxv)
{
	const DumpContext *dctx = (DumpContext *) dctxv;
	TableInfo  *tbinfo = &dctx->tblinfo[dctx->tblidx];
	const char *classname = tbinfo->relname;
	const bool	hasoids = tbinfo->hasoids;
	const bool	oids = dctx->oids;
	PQExpBuffer q = createPQExpBuffer();
	PGresult   *res;
	int			ret;
	bool		copydone;
	char		copybuf[COPYBUFSIZ];
845

846 847
	if (g_verbose)
		write_msg(NULL, "dumping out the contents of table %s\n", classname);
848

849 850 851 852 853 854 855
	/*
	 * Make sure we are in proper schema.  We will qualify the table name
	 * below anyway (in case its name conflicts with a pg_catalog table);
	 * but this ensures reproducible results in case the table contains
	 * regproc, regclass, etc columns.
	 */
	selectSourceSchema(tbinfo->relnamespace->nspname);
856

857
	if (oids && hasoids)
B
Bruce Momjian 已提交
858
	{
859 860 861
		appendPQExpBuffer(q, "COPY %s WITH OIDS TO stdout;",
						  fmtQualifiedId(tbinfo->relnamespace->nspname,
										 classname));
P
Philip Warner 已提交
862
	}
863
	else
B
Bruce Momjian 已提交
864
	{
865 866 867
		appendPQExpBuffer(q, "COPY %s TO stdout;",
						  fmtQualifiedId(tbinfo->relnamespace->nspname,
										 classname));
B
Bruce Momjian 已提交
868
	}
869 870 871
	res = PQexec(g_conn, q->data);
	if (!res ||
		PQresultStatus(res) == PGRES_FATAL_ERROR)
872
	{
873 874 875 876 877
		write_msg(NULL, "SQL command to dump the contents of table \"%s\" failed\n",
				  classname);
		write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
		write_msg(NULL, "The command was: %s\n", q->data);
		exit_nicely();
878
	}
879
	if (PQresultStatus(res) != PGRES_COPY_OUT)
880
	{
881 882 883 884 885 886
		write_msg(NULL, "SQL command to dump the contents of table \"%s\" executed abnormally.\n",
				  classname);
		write_msg(NULL, "The server returned status %d when %d was expected.\n",
				  PQresultStatus(res), PGRES_COPY_OUT);
		write_msg(NULL, "The command was: %s\n", q->data);
		exit_nicely();
887
	}
888

889
	copydone = false;
P
Philip Warner 已提交
890

891
	while (!copydone)
B
Bruce Momjian 已提交
892
	{
893
		ret = PQgetline(g_conn, copybuf, COPYBUFSIZ);
B
Bruce Momjian 已提交
894

895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
		if (copybuf[0] == '\\' &&
			copybuf[1] == '.' &&
			copybuf[2] == '\0')
		{
			copydone = true;	/* don't print this... */
		}
		else
		{
			archputs(copybuf, fout);
			switch (ret)
			{
				case EOF:
					copydone = true;
					/* FALLTHROUGH */
				case 0:
					archputc('\n', fout);
					break;
				case 1:
					break;
			}
		}
B
Bruce Momjian 已提交
916

917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
		/*
		 * THROTTLE:
		 *
		 * There was considerable discussion in late July, 2000
		 * regarding slowing down pg_dump when backing up large
		 * tables. Users with both slow & fast (muti-processor)
		 * machines experienced performance degradation when doing
		 * a backup.
		 *
		 * Initial attempts based on sleeping for a number of ms for
		 * each ms of work were deemed too complex, then a simple
		 * 'sleep in each loop' implementation was suggested. The
		 * latter failed because the loop was too tight. Finally,
		 * the following was implemented:
		 *
		 * If throttle is non-zero, then See how long since the last
		 * sleep. Work out how long to sleep (based on ratio). If
		 * sleep is more than 100ms, then sleep reset timer EndIf
		 * EndIf
		 *
		 * where the throttle value was the number of ms to sleep per
		 * ms of work. The calculation was done in each loop.
		 *
		 * Most of the hard work is done in the backend, and this
		 * solution still did not work particularly well: on slow
		 * machines, the ratio was 50:1, and on medium paced
		 * machines, 1:1, and on fast multi-processor machines, it
		 * had little or no effect, for reasons that were unclear.
		 *
		 * Further discussion ensued, and the proposal was dropped.
		 *
		 * For those people who want this feature, it can be
		 * implemented using gettimeofday in each loop,
		 * calculating the time since last sleep, multiplying that
		 * by the sleep ratio, then if the result is more than a
		 * preset 'minimum sleep time' (say 100ms), call the
		 * 'select' function to sleep for a subsecond period ie.
		 *
		 * select(0, NULL, NULL, NULL, &tvi);
		 *
		 * This will return after the interval specified in the
		 * structure tvi. Fianally, call gettimeofday again to
		 * save the 'last sleep time'.
		 */
B
Bruce Momjian 已提交
961
	}
962
	archprintf(fout, "\\.\n");
B
Bruce Momjian 已提交
963

964 965
	ret = PQendcopy(g_conn);
	if (ret != 0)
B
Bruce Momjian 已提交
966
	{
967 968 969 970
		write_msg(NULL, "SQL command to dump the contents of table \"%s\" failed: PQendcopy() failed.\n", classname);
		write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
		write_msg(NULL, "The command was: %s\n", q->data);
		exit_nicely();
971 972
	}

973
	PQclear(res);
974 975 976
	destroyPQExpBuffer(q);
	return 1;
}
977

978 979 980 981 982 983 984 985 986 987
static int
dumpClasses_dumpData(Archive *fout, char *oid, void *dctxv)
{
	const DumpContext *dctx = (DumpContext *) dctxv;
	TableInfo  *tbinfo = &dctx->tblinfo[dctx->tblidx];
	const char *classname = tbinfo->relname;
	PQExpBuffer q = createPQExpBuffer();
	PGresult   *res;
	int			tuple;
	int			field;
988

989
	/*
990 991 992 993
	 * Make sure we are in proper schema.  We will qualify the table name
	 * below anyway (in case its name conflicts with a pg_catalog table);
	 * but this ensures reproducible results in case the table contains
	 * regproc, regclass, etc columns.
994
	 */
995
	selectSourceSchema(tbinfo->relnamespace->nspname);
996

997 998 999 1000 1001 1002
	if (fout->remoteVersion >= 70100)
	{
		appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
						  "SELECT * FROM ONLY %s",
						  fmtQualifiedId(tbinfo->relnamespace->nspname,
										 classname));
1003
	}
1004
	else
1005 1006 1007 1008 1009 1010
	{
		appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
						  "SELECT * FROM %s",
						  fmtQualifiedId(tbinfo->relnamespace->nspname,
										 classname));
	}
1011

1012 1013 1014 1015 1016 1017 1018 1019 1020
	res = PQexec(g_conn, q->data);
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		write_msg(NULL, "dumpClasses(): SQL command failed\n");
		write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
		write_msg(NULL, "The command was: %s\n", q->data);
		exit_nicely();
	}
1021

1022 1023 1024
	do
	{
		PQclear(res);
B
Bruce Momjian 已提交
1025

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
		res = PQexec(g_conn, "FETCH 100 FROM _pg_dump_cursor");
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
			write_msg(NULL, "dumpClasses(): SQL command failed\n");
			write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
			write_msg(NULL, "The command was: FETCH 100 FROM _pg_dump_cursor\n");
			exit_nicely();
		}

		for (tuple = 0; tuple < PQntuples(res); tuple++)
		{
			archprintf(fout, "INSERT INTO %s ", fmtId(classname, force_quotes));
			if (attrNames == true)
			{
				resetPQExpBuffer(q);
				appendPQExpBuffer(q, "(");
				for (field = 0; field < PQnfields(res); field++)
				{
					if (field > 0)
						appendPQExpBuffer(q, ",");
					appendPQExpBuffer(q, fmtId(PQfname(res, field), force_quotes));
				}
				appendPQExpBuffer(q, ") ");
				archprintf(fout, "%s", q->data);
			}
			archprintf(fout, "VALUES (");
			for (field = 0; field < PQnfields(res); field++)
			{
				if (field > 0)
					archprintf(fout, ",");
				if (PQgetisnull(res, tuple, field))
				{
					archprintf(fout, "NULL");
					continue;
				}
				switch (PQftype(res, field))
				{
					case INT2OID:
					case INT4OID:
					case OIDOID:		/* int types */
					case FLOAT4OID:
					case FLOAT8OID:		/* float types */
						/* These types are printed without quotes */
						archprintf(fout, "%s",
								   PQgetvalue(res, tuple, field));
						break;
					case BITOID:
					case VARBITOID:
						archprintf(fout, "B'%s'",
								   PQgetvalue(res, tuple, field));
						break;
					default:
1079

1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
						/*
						 * All other types are printed as string literals,
						 * with appropriate escaping of special
						 * characters.
						 */
						resetPQExpBuffer(q);
						formatStringLiteral(q, PQgetvalue(res, tuple, field), CONV_ALL);
						archprintf(fout, "%s", q->data);
						break;
				}
			}
			archprintf(fout, ");\n");
		}
1093

1094 1095
	} while (PQntuples(res) > 0);
	PQclear(res);
1096

1097 1098 1099
	res = PQexec(g_conn, "CLOSE _pg_dump_cursor");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
V
Vadim B. Mikheev 已提交
1100
	{
1101 1102 1103 1104
		write_msg(NULL, "dumpClasses(): SQL command failed\n");
		write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
		write_msg(NULL, "The command was: CLOSE _pg_dump_cursor\n");
		exit_nicely();
V
Vadim B. Mikheev 已提交
1105
	}
1106
	PQclear(res);
1107

1108 1109 1110
	destroyPQExpBuffer(q);
	return 1;
}
1111

1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
/*
 * Convert a string value to an SQL string literal,
 * with appropriate escaping of special characters.
 * Quote mark ' goes to '' per SQL standard, other
 * stuff goes to \ sequences.
 * The literal is appended to the given PQExpBuffer.
 */
static void
formatStringLiteral(PQExpBuffer buf, const char *str, const formatLiteralOptions opts)
{
	appendPQExpBufferChar(buf, '\'');
	while (*str)
B
Bruce Momjian 已提交
1124
	{
1125
		char		ch = *str++;
1126

1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
		if (ch == '\\' || ch == '\'')
		{
			appendPQExpBufferChar(buf, ch);		/* double these */
			appendPQExpBufferChar(buf, ch);
		}
		else if ((unsigned char) ch < (unsigned char) ' ' &&
				 (opts == CONV_ALL
				  || (ch != '\n' && ch != '\t')
				  ))
		{
			/*
			 * generate octal escape for control chars other than
			 * whitespace
			 */
			appendPQExpBufferChar(buf, '\\');
			appendPQExpBufferChar(buf, ((ch >> 6) & 3) + '0');
			appendPQExpBufferChar(buf, ((ch >> 3) & 7) + '0');
			appendPQExpBufferChar(buf, (ch & 7) + '0');
		}
1146
		else
1147 1148 1149 1150
			appendPQExpBufferChar(buf, ch);
	}
	appendPQExpBufferChar(buf, '\'');
}
B
Bruce Momjian 已提交
1151

1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
/*
 * DumpClasses -
 *	  dump the contents of all the classes.
 */
static void
dumpClasses(const TableInfo *tblinfo, const int numTables, Archive *fout,
			const bool oids)
{
	int			i;
	DataDumperPtr dumpFn;
	DumpContext *dumpCtx;
	char		copyBuf[512];
	char	   *copyStmt;
B
Bruce Momjian 已提交
1165

1166 1167 1168
	for (i = 0; i < numTables; i++)
	{
		const char *classname = tblinfo[i].relname;
1169

1170 1171 1172
		/* Skip VIEW relations */
		if (tblinfo[i].relkind == RELKIND_VIEW)
			continue;
B
Bruce Momjian 已提交
1173

1174 1175
		if (tblinfo[i].relkind == RELKIND_SEQUENCE)		/* already dumped */
			continue;
1176

1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
		if (tblinfo[i].dump)
		{
			if (g_verbose)
				write_msg(NULL, "preparing to dump the contents of table %s\n",
						  classname);

			dumpCtx = (DumpContext *) malloc(sizeof(DumpContext));
			dumpCtx->tblinfo = (TableInfo *) tblinfo;
			dumpCtx->tblidx = i;
			dumpCtx->oids = oids;

			if (!dumpData)
			{
				/* Dump/restore using COPY */
				dumpFn = dumpClasses_nodumpData;
				sprintf(copyBuf, "COPY %s %sFROM stdin;\n",
						fmtId(tblinfo[i].relname, force_quotes),
						(oids && tblinfo[i].hasoids) ? "WITH OIDS " : "");
				copyStmt = copyBuf;
			}
			else
			{
				/* Restore using INSERT */
				dumpFn = dumpClasses_dumpData;
				copyStmt = NULL;
			}

			ArchiveEntry(fout, tblinfo[i].oid, tblinfo[i].relname,
						 tblinfo[i].relnamespace->nspname, tblinfo[i].usename,
						 "TABLE DATA", NULL, "", "", copyStmt,
						 dumpFn, dumpCtx);
		}
	}
1210 1211
}

1212

1213 1214 1215 1216
/*
 * dumpDatabase:
 *	dump the database definition
 */
B
Bruce Momjian 已提交
1217
static int
1218 1219
dumpDatabase(Archive *AH)
{
B
Bruce Momjian 已提交
1220 1221 1222 1223 1224
	PQExpBuffer dbQry = createPQExpBuffer();
	PQExpBuffer delQry = createPQExpBuffer();
	PQExpBuffer creaQry = createPQExpBuffer();
	PGresult   *res;
	int			ntups;
1225 1226 1227 1228 1229 1230 1231 1232 1233
	int			i_dba,
				i_encoding,
				i_datpath;
	const char *datname,
			   *dba,
			   *encoding,
			   *datpath;

	datname = PQdb(g_conn);
1234 1235

	if (g_verbose)
1236
		write_msg(NULL, "saving database definition\n");
1237

1238 1239 1240
	/* Make sure we are in proper schema */
	selectSourceSchema("pg_catalog");

1241 1242 1243
	/* Get the database owner and parameters from pg_database */
	appendPQExpBuffer(dbQry, "select (select usename from pg_user where usesysid = datdba) as dba,"
					  " encoding, datpath from pg_database"
B
Bruce Momjian 已提交
1244
					  " where datname = ");
1245
	formatStringLiteral(dbQry, datname, CONV_ALL);
1246 1247 1248 1249 1250

	res = PQexec(g_conn, dbQry->data);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1251 1252 1253
		write_msg(NULL, "SQL command failed\n");
		write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
		write_msg(NULL, "The command was: %s\n", dbQry->data);
1254
		exit_nicely();
1255 1256 1257 1258
	}

	ntups = PQntuples(res);

1259 1260
	if (ntups <= 0)
	{
1261 1262
		write_msg(NULL, "missing pg_database entry for database \"%s\"\n",
				  datname);
1263
		exit_nicely();
1264 1265
	}

1266 1267
	if (ntups != 1)
	{
1268
		write_msg(NULL, "query returned more than one (%d) pg_database entry for database \"%s\"\n",
1269
				  ntups, datname);
1270
		exit_nicely();
1271 1272 1273
	}

	i_dba = PQfnumber(res, "dba");
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
	i_encoding = PQfnumber(res, "encoding");
	i_datpath = PQfnumber(res, "datpath");
	dba = PQgetvalue(res, 0, i_dba);
	encoding = PQgetvalue(res, 0, i_encoding);
	datpath = PQgetvalue(res, 0, i_datpath);

	appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
					  fmtId(datname, force_quotes));
	if (strlen(encoding) > 0)
		appendPQExpBuffer(creaQry, " ENCODING = %s", encoding);
	if (strlen(datpath) > 0)
		appendPQExpBuffer(creaQry, " LOCATION = '%s'", datpath);
	appendPQExpBuffer(creaQry, ";\n");

	appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
					  fmtId(datname, force_quotes));

1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
	ArchiveEntry(AH, "0",		/* OID */
				 datname,		/* Name */
				 NULL,			/* Namespace */
				 dba,			/* Owner */
				 "DATABASE",	/* Desc */
				 NULL,			/* Deps */
				 creaQry->data,	/* Create */
				 delQry->data,	/* Del */
				 NULL,			/* Copy */
				 NULL,			/* Dumper */
				 NULL);			/* Dumper Arg */
1302 1303 1304

	PQclear(res);

1305 1306 1307 1308
	destroyPQExpBuffer(dbQry);
	destroyPQExpBuffer(delQry);
	destroyPQExpBuffer(creaQry);

1309 1310 1311 1312
	return 1;
}


1313 1314 1315 1316 1317 1318
/*
 * dumpBlobs:
 *	dump all blobs
 *
 */

B
Bruce Momjian 已提交
1319
#define loBufSize 16384
1320 1321
#define loFetchSize 1000

B
Bruce Momjian 已提交
1322 1323
static int
dumpBlobs(Archive *AH, char *junkOid, void *junkVal)
1324
{
B
Bruce Momjian 已提交
1325 1326 1327 1328 1329 1330 1331
	PQExpBuffer oidQry = createPQExpBuffer();
	PQExpBuffer oidFetchQry = createPQExpBuffer();
	PGresult   *res;
	int			i;
	int			loFd;
	char		buf[loBufSize];
	int			cnt;
1332
	Oid			blobOid;
1333 1334

	if (g_verbose)
1335
		write_msg(NULL, "saving large objects\n");
1336

1337 1338 1339
	/* Make sure we are in proper schema */
	selectSourceSchema("pg_catalog");

1340
	/* Cursor to get all BLOB tables */
1341 1342
	if (AH->remoteVersion >= 70100)
		appendPQExpBuffer(oidQry, "Declare blobOid Cursor for SELECT DISTINCT loid FROM pg_largeobject");
1343
	else
1344
		appendPQExpBuffer(oidQry, "Declare blobOid Cursor for SELECT oid from pg_class where relkind = 'l'");
1345 1346 1347 1348

	res = PQexec(g_conn, oidQry->data);
	if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
	{
1349
		write_msg(NULL, "dumpBlobs(): cursor declaration failed: %s", PQerrorMessage(g_conn));
1350
		exit_nicely();
1351 1352 1353 1354 1355
	}

	/* Fetch for cursor */
	appendPQExpBuffer(oidFetchQry, "Fetch %d in blobOid", loFetchSize);

B
Bruce Momjian 已提交
1356 1357
	do
	{
1358 1359 1360 1361 1362 1363
		/* Do a fetch */
		PQclear(res);
		res = PQexec(g_conn, oidFetchQry->data);

		if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
		{
1364 1365
			write_msg(NULL, "dumpBlobs(): fetch from cursor failed: %s",
					  PQerrorMessage(g_conn));
1366
			exit_nicely();
1367 1368 1369 1370 1371
		}

		/* Process the tuples, if any */
		for (i = 0; i < PQntuples(res); i++)
		{
1372
			blobOid = atooid(PQgetvalue(res, i, 0));
1373 1374 1375 1376
			/* Open the BLOB */
			loFd = lo_open(g_conn, blobOid, INV_READ);
			if (loFd == -1)
			{
1377 1378
				write_msg(NULL, "dumpBlobs(): could not open large object: %s",
						  PQerrorMessage(g_conn));
1379
				exit_nicely();
1380 1381 1382 1383
			}

			StartBlob(AH, blobOid);

1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
			/* Now read it in chunks, sending data to archive */
			do
			{
				cnt = lo_read(g_conn, loFd, buf, loBufSize);
				if (cnt < 0)
				{
					write_msg(NULL, "dumpBlobs(): error reading large object: %s",
							  PQerrorMessage(g_conn));
					exit_nicely();
				}
1394

1395
				WriteData(AH, buf, cnt);
1396

1397
			} while (cnt > 0);
1398

1399
			lo_close(g_conn, loFd);
1400

1401
			EndBlob(AH, blobOid);
1402

1403 1404
		}
	} while (PQntuples(res) > 0);
1405

1406 1407
	destroyPQExpBuffer(oidQry);
	destroyPQExpBuffer(oidFetchQry);
1408

1409
	return 1;
1410 1411 1412
}

/*
1413 1414 1415
 * getNamespaces:
 *	  read all namespaces in the system catalogs and return them in the
 * NamespaceInfo* structure
1416
 *
1417
 *	numNamespaces is set to the number of namespaces read in
1418
 */
1419 1420
NamespaceInfo *
getNamespaces(int *numNamespaces)
1421
{
1422
	PGresult   *res;
1423 1424
	int			ntups;
	int			i;
1425 1426
	PQExpBuffer query;
	NamespaceInfo *nsinfo;
1427
	int			i_oid;
1428
	int			i_nspname;
1429
	int			i_usename;
1430
	int			i_nspacl;
1431 1432

	/*
1433 1434
	 * Before 7.3, there are no real namespaces; create two dummy entries,
	 * one for user stuff and one for system stuff.
1435
	 */
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
	if (g_fout->remoteVersion < 70300)
	{
		nsinfo = (NamespaceInfo *) malloc(2 * sizeof(NamespaceInfo));

		nsinfo[0].oid = strdup("0");
		nsinfo[0].nspname = strdup("");
		nsinfo[0].usename = strdup("");
		nsinfo[0].nspacl = strdup("");

		selectDumpableNamespace(&nsinfo[0]);

		nsinfo[1].oid = strdup("1");
		nsinfo[1].nspname = strdup("pg_catalog");
		nsinfo[1].usename = strdup("");
		nsinfo[1].nspacl = strdup("");

		selectDumpableNamespace(&nsinfo[1]);

		g_namespaces = nsinfo;
		g_numNamespaces = *numNamespaces = 2;

		return nsinfo;
	}

	query = createPQExpBuffer();

	/* Make sure we are in proper schema */
	selectSourceSchema("pg_catalog");
1464

1465 1466 1467 1468 1469 1470 1471 1472
	/*
	 * we fetch all namespaces including system ones, so that every object
	 * we read in can be linked to a containing namespace.
	 */
	appendPQExpBuffer(query, "SELECT oid, nspname, "
						  "(select usename from pg_user where nspowner = usesysid) as usename, "
						  "nspacl "
						  "FROM pg_namespace");
1473

B
Hi, all  
Bruce Momjian 已提交
1474
	res = PQexec(g_conn, query->data);
1475 1476 1477
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1478
		write_msg(NULL, "query to obtain list of namespaces failed: %s", PQerrorMessage(g_conn));
1479
		exit_nicely();
1480 1481 1482 1483
	}

	ntups = PQntuples(res);

1484
	nsinfo = (NamespaceInfo *) malloc(ntups * sizeof(NamespaceInfo));
1485 1486

	i_oid = PQfnumber(res, "oid");
1487
	i_nspname = PQfnumber(res, "nspname");
1488
	i_usename = PQfnumber(res, "usename");
1489
	i_nspacl = PQfnumber(res, "nspacl");
1490 1491 1492

	for (i = 0; i < ntups; i++)
	{
1493 1494 1495 1496
		nsinfo[i].oid = strdup(PQgetvalue(res, i, i_oid));
		nsinfo[i].nspname = strdup(PQgetvalue(res, i, i_nspname));
		nsinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
		nsinfo[i].nspacl = strdup(PQgetvalue(res, i, i_nspacl));
1497

1498 1499
		/* Decide whether to dump this namespace */
		selectDumpableNamespace(&nsinfo[i]);
1500

1501 1502 1503
		if (strlen(nsinfo[i].usename) == 0)
			write_msg(NULL, "WARNING: owner of namespace %s appears to be invalid\n",
					  nsinfo[i].nspname);
1504 1505 1506
	}

	PQclear(res);
1507 1508
	destroyPQExpBuffer(query);

1509 1510
	g_namespaces = nsinfo;
	g_numNamespaces = *numNamespaces = ntups;
1511

1512
	return nsinfo;
1513 1514
}

1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
/*
 * findNamespace:
 *		given a namespace OID and an object OID, look up the info read by
 *		getNamespaces
 *
 * NB: for pre-7.3 source database, we use object OID to guess whether it's
 * a system object or not.  In 7.3 and later there is no guessing.
 */
static NamespaceInfo *
findNamespace(const char *nsoid, const char *objoid)
1525
{
1526
	int			i;
1527

1528
	if (g_fout->remoteVersion >= 70300)
1529
	{
1530
		for (i = 0; i < g_numNamespaces; i++)
1531
		{
1532
			NamespaceInfo  *nsinfo = &g_namespaces[i];
B
Bruce Momjian 已提交
1533

1534 1535
			if (strcmp(nsoid, nsinfo->oid) == 0)
				return nsinfo;
B
Bruce Momjian 已提交
1536
		}
1537 1538
		write_msg(NULL, "Failed to find namespace with OID %s.\n", nsoid);
		exit_nicely();
1539
	}
1540 1541 1542 1543 1544 1545 1546 1547
	else
	{
		/* This code depends on the layout set up by getNamespaces. */
		if (atooid(objoid) > g_last_builtin_oid)
			i = 0;				/* user object */
		else
			i = 1;				/* system object */
		return &g_namespaces[i];
1548 1549
	}

1550
	return NULL;				/* keep compiler quiet */
1551
}
1552 1553

/*
1554 1555 1556
 * getTypes:
 *	  read all types in the system catalogs and return them in the
 * TypeInfo* structure
1557
 *
1558
 *	numTypes is set to the number of types read in
1559
 */
1560 1561
TypeInfo *
getTypes(int *numTypes)
1562
{
B
Bruce Momjian 已提交
1563
	PGresult   *res;
1564 1565
	int			ntups;
	int			i;
1566
	PQExpBuffer query = createPQExpBuffer();
1567
	TypeInfo   *tinfo;
1568
	int			i_oid;
1569 1570
	int			i_typname;
	int			i_typnamespace;
1571
	int			i_usename;
1572 1573 1574 1575
	int			i_typelem;
	int			i_typrelid;
	int			i_typtype;
	int			i_typisdefined;
1576

1577 1578 1579 1580 1581
	/*
	 * we include even the built-in types because those may be used as
	 * array elements by user-defined types
	 *
	 * we filter out the built-in types when we dump out the types
1582 1583
	 *
	 * same approach for undefined (shell) types
1584
	 */
1585

1586 1587 1588 1589
	/* Make sure we are in proper schema */
	selectSourceSchema("pg_catalog");

	if (g_fout->remoteVersion >= 70300)
1590
	{
1591 1592 1593 1594 1595
		appendPQExpBuffer(query, "SELECT pg_type.oid, typname, "
						  "typnamespace, "
						  "(select usename from pg_user where typowner = usesysid) as usename, "
						  "typelem, typrelid, typtype, typisdefined "
						  "FROM pg_type");
1596
	}
1597 1598
	else
	{
1599 1600 1601 1602 1603
		appendPQExpBuffer(query, "SELECT pg_type.oid, typname, "
						  "0::oid as typnamespace, "
						  "(select usename from pg_user where typowner = usesysid) as usename, "
						  "typelem, typrelid, typtype, typisdefined "
						  "FROM pg_type");
1604
	}
1605

B
Hi, all  
Bruce Momjian 已提交
1606
	res = PQexec(g_conn, query->data);
1607 1608 1609
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1610
		write_msg(NULL, "query to obtain list of data types failed: %s", PQerrorMessage(g_conn));
1611
		exit_nicely();
1612 1613 1614 1615
	}

	ntups = PQntuples(res);

1616
	tinfo = (TypeInfo *) malloc(ntups * sizeof(TypeInfo));
1617 1618

	i_oid = PQfnumber(res, "oid");
1619 1620
	i_typname = PQfnumber(res, "typname");
	i_typnamespace = PQfnumber(res, "typnamespace");
1621
	i_usename = PQfnumber(res, "usename");
1622 1623 1624 1625
	i_typelem = PQfnumber(res, "typelem");
	i_typrelid = PQfnumber(res, "typrelid");
	i_typtype = PQfnumber(res, "typtype");
	i_typisdefined = PQfnumber(res, "typisdefined");
1626 1627 1628

	for (i = 0; i < ntups; i++)
	{
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
		tinfo[i].oid = strdup(PQgetvalue(res, i, i_oid));
		tinfo[i].typname = strdup(PQgetvalue(res, i, i_typname));
		tinfo[i].typnamespace = findNamespace(PQgetvalue(res, i, i_typnamespace),
											  tinfo[i].oid);
		tinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
		tinfo[i].typelem = strdup(PQgetvalue(res, i, i_typelem));
		tinfo[i].typrelid = strdup(PQgetvalue(res, i, i_typrelid));
		tinfo[i].typtype = *PQgetvalue(res, i, i_typtype);

		/*
		 * check for user-defined array types, omit system generated ones
		 */
		if ((strcmp(tinfo[i].typelem, "0") != 0) &&
			tinfo[i].typname[0] != '_')
			tinfo[i].isArray = true;
		else
			tinfo[i].isArray = false;
1646

1647 1648 1649 1650
		if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
			tinfo[i].isDefined = true;
		else
			tinfo[i].isDefined = false;
1651 1652 1653 1654

		if (strlen(tinfo[i].usename) == 0 && tinfo[i].isDefined)
			write_msg(NULL, "WARNING: owner of data type %s appears to be invalid\n",
					  tinfo[i].typname);
1655 1656
	}

1657 1658
	*numTypes = ntups;

1659 1660
	PQclear(res);

1661 1662
	destroyPQExpBuffer(query);

1663
	return tinfo;
1664 1665 1666
}

/*
1667 1668 1669
 * getOperators:
 *	  read all operators in the system catalogs and return them in the
 * OprInfo* structure
1670
 *
1671
 *	numOprs is set to the number of operators read in
1672
 */
1673 1674
OprInfo *
getOperators(int *numOprs)
1675
{
1676
	PGresult   *res;
1677 1678
	int			ntups;
	int			i;
1679
	PQExpBuffer query = createPQExpBuffer();
1680
	OprInfo    *oprinfo;
1681
	int			i_oid;
1682 1683
	int			i_oprname;
	int			i_oprnamespace;
1684
	int			i_usename;
1685
	int			i_oprcode;
1686

1687 1688 1689 1690
	/*
	 * find all operators, including builtin operators;
	 * we filter out system-defined operators at dump-out time.
	 */
1691

1692 1693 1694 1695
	/* Make sure we are in proper schema */
	selectSourceSchema("pg_catalog");

	if (g_fout->remoteVersion >= 70300)
1696
	{
1697 1698 1699 1700 1701
		appendPQExpBuffer(query, "SELECT pg_operator.oid, oprname, "
						  "oprnamespace, "
						  "(select usename from pg_user where oprowner = usesysid) as usename, "
						  "oprcode::oid "
						  "from pg_operator");
1702 1703 1704
	}
	else
	{
1705 1706 1707 1708 1709
		appendPQExpBuffer(query, "SELECT pg_operator.oid, oprname, "
						  "0::oid as oprnamespace, "
						  "(select usename from pg_user where oprowner = usesysid) as usename, "
						  "oprcode::oid "
						  "from pg_operator");
1710
	}
1711

B
Hi, all  
Bruce Momjian 已提交
1712
	res = PQexec(g_conn, query->data);
1713 1714 1715
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1716
		write_msg(NULL, "query to obtain list of operators failed: %s", PQerrorMessage(g_conn));
1717
		exit_nicely();
1718 1719 1720
	}

	ntups = PQntuples(res);
1721
	*numOprs = ntups;
1722

1723
	oprinfo = (OprInfo *) malloc(ntups * sizeof(OprInfo));
1724

1725
	i_oid = PQfnumber(res, "oid");
1726 1727
	i_oprname = PQfnumber(res, "oprname");
	i_oprnamespace = PQfnumber(res, "oprnamespace");
1728
	i_usename = PQfnumber(res, "usename");
1729
	i_oprcode = PQfnumber(res, "oprcode");
1730 1731 1732

	for (i = 0; i < ntups; i++)
	{
1733 1734 1735 1736 1737 1738
		oprinfo[i].oid = strdup(PQgetvalue(res, i, i_oid));
		oprinfo[i].oprname = strdup(PQgetvalue(res, i, i_oprname));
		oprinfo[i].oprnamespace = findNamespace(PQgetvalue(res, i, i_oprnamespace),
												oprinfo[i].oid);
		oprinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
		oprinfo[i].oprcode = strdup(PQgetvalue(res, i, i_oprcode));
1739

1740 1741 1742
		if (strlen(oprinfo[i].usename) == 0)
			write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
					  oprinfo[i].oprname);
1743 1744 1745 1746
	}

	PQclear(res);

1747
	destroyPQExpBuffer(query);
1748

1749
	return oprinfo;
1750 1751 1752
}

/*
1753 1754 1755
 * getAggregates:
 *	  read all the user-defined aggregates in the system catalogs and
 * return them in the AggInfo* structure
1756
 *
1757
 * numAggs is set to the number of aggregates read in
1758
 */
1759 1760
AggInfo *
getAggregates(int *numAggs)
1761
{
1762
	PGresult   *res;
1763 1764
	int			ntups;
	int			i;
1765
	PQExpBuffer query = createPQExpBuffer();
1766
	AggInfo    *agginfo;
1767

1768 1769 1770
	int			i_oid;
	int			i_aggname;
	int			i_aggnamespace;
1771
	int			i_aggbasetype;
1772
	int			i_usename;
1773
	int			i_aggacl;
1774

1775 1776
	/* Make sure we are in proper schema */
	selectSourceSchema("pg_catalog");
1777

1778 1779 1780
	/* find all user-defined aggregates */

	if (g_fout->remoteVersion >= 70300)
1781
	{
1782 1783
		appendPQExpBuffer(query, "SELECT pg_proc.oid, proname as aggname, "
						  "pronamespace as aggnamespace, "
1784
						  "proargtypes[0] as aggbasetype, "
1785 1786
						  "(select usename from pg_user where proowner = usesysid) as usename, "
						  "proacl as aggacl "
1787 1788 1789 1790
						  "FROM pg_proc "
						  "WHERE proisagg "
						  "AND pronamespace != "
						  "(select oid from pg_namespace where nspname = 'pg_catalog')");
1791 1792 1793
	}
	else
	{
1794 1795
		appendPQExpBuffer(query, "SELECT pg_aggregate.oid, aggname, "
						  "0::oid as aggnamespace, "
1796
						  "aggbasetype, "
1797
						  "(select usename from pg_user where aggowner = usesysid) as usename, "
1798
						  "'{=X}' as aggacl "
1799 1800 1801
						  "from pg_aggregate "
						  "where oid > '%u'::oid",
						  g_last_builtin_oid);
1802
	}
1803

B
Hi, all  
Bruce Momjian 已提交
1804
	res = PQexec(g_conn, query->data);
1805 1806 1807
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1808
		write_msg(NULL, "query to obtain list of aggregate functions failed: %s",
1809
				  PQerrorMessage(g_conn));
1810
		exit_nicely();
1811 1812 1813
	}

	ntups = PQntuples(res);
1814
	*numAggs = ntups;
1815

1816
	agginfo = (AggInfo *) malloc(ntups * sizeof(AggInfo));
1817

1818 1819 1820
	i_oid = PQfnumber(res, "oid");
	i_aggname = PQfnumber(res, "aggname");
	i_aggnamespace = PQfnumber(res, "aggnamespace");
1821
	i_aggbasetype = PQfnumber(res, "aggbasetype");
1822
	i_usename = PQfnumber(res, "usename");
1823
	i_aggacl = PQfnumber(res, "aggacl");
1824 1825 1826

	for (i = 0; i < ntups; i++)
	{
1827 1828 1829 1830
		agginfo[i].oid = strdup(PQgetvalue(res, i, i_oid));
		agginfo[i].aggname = strdup(PQgetvalue(res, i, i_aggname));
		agginfo[i].aggnamespace = findNamespace(PQgetvalue(res, i, i_aggnamespace),
												agginfo[i].oid);
1831
		agginfo[i].aggbasetype = strdup(PQgetvalue(res, i, i_aggbasetype));
1832 1833 1834 1835
		agginfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
		if (strlen(agginfo[i].usename) == 0)
			write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
					  agginfo[i].aggname);
1836
		agginfo[i].aggacl = strdup(PQgetvalue(res, i, i_aggacl));
1837
		agginfo[i].fmtbasetype = NULL; /* computed when it's dumped */
1838
	}
1839

1840
	PQclear(res);
1841

1842
	destroyPQExpBuffer(query);
1843

1844 1845
	return agginfo;
}
1846

1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
/*
 * getFuncs:
 *	  read all the user-defined functions in the system catalogs and
 * return them in the FuncInfo* structure
 *
 * numFuncs is set to the number of functions read in
 */
FuncInfo *
getFuncs(int *numFuncs)
{
	PGresult   *res;
	int			ntups;
	int			i;
	PQExpBuffer query = createPQExpBuffer();
	FuncInfo   *finfo;
1862

1863 1864 1865 1866 1867 1868 1869 1870
	int			i_oid;
	int			i_proname;
	int			i_pronamespace;
	int			i_usename;
	int			i_prolang;
	int			i_pronargs;
	int			i_proargtypes;
	int			i_prorettype;
1871
	int			i_proacl;
1872

1873 1874
	/* Make sure we are in proper schema */
	selectSourceSchema("pg_catalog");
B
Bruce Momjian 已提交
1875

1876
	/* find all user-defined funcs */
1877

1878 1879 1880 1881
	if (g_fout->remoteVersion >= 70300)
	{
		appendPQExpBuffer(query,
						  "SELECT pg_proc.oid, proname, prolang, "
1882
						  "pronargs, proargtypes, prorettype, proacl, "
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
						  "pronamespace, "
						  "(select usename from pg_user where proowner = usesysid) as usename "
						  "FROM pg_proc "
						  "WHERE NOT proisagg "
						  "AND pronamespace != "
						  "(select oid from pg_namespace where nspname = 'pg_catalog')");
	}
	else
	{
		appendPQExpBuffer(query,
						  "SELECT pg_proc.oid, proname, prolang, "
						  "pronargs, proargtypes, prorettype, "
1895
						  "'{=X}' as proacl, "
1896 1897 1898 1899 1900 1901
						  "0::oid as pronamespace, "
						  "(select usename from pg_user where proowner = usesysid) as usename "
						  "FROM pg_proc "
						  "where pg_proc.oid > '%u'::oid",
						  g_last_builtin_oid);
	}
1902

1903 1904 1905 1906 1907 1908 1909 1910
	res = PQexec(g_conn, query->data);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		write_msg(NULL, "query to obtain list of functions failed: %s",
				  PQerrorMessage(g_conn));
		exit_nicely();
	}
1911

1912
	ntups = PQntuples(res);
B
Bruce Momjian 已提交
1913

1914
	*numFuncs = ntups;
1915

1916
	finfo = (FuncInfo *) malloc(ntups * sizeof(FuncInfo));
1917

1918
	memset((char *) finfo, 0, ntups * sizeof(FuncInfo));
1919

1920 1921 1922 1923 1924 1925 1926 1927
	i_oid = PQfnumber(res, "oid");
	i_proname = PQfnumber(res, "proname");
	i_pronamespace = PQfnumber(res, "pronamespace");
	i_usename = PQfnumber(res, "usename");
	i_prolang = PQfnumber(res, "prolang");
	i_pronargs = PQfnumber(res, "pronargs");
	i_proargtypes = PQfnumber(res, "proargtypes");
	i_prorettype = PQfnumber(res, "prorettype");
1928
	i_proacl = PQfnumber(res, "proacl");
1929

1930 1931 1932 1933 1934 1935 1936 1937 1938
	for (i = 0; i < ntups; i++)
	{
		finfo[i].oid = strdup(PQgetvalue(res, i, i_oid));
		finfo[i].proname = strdup(PQgetvalue(res, i, i_proname));
		finfo[i].pronamespace = findNamespace(PQgetvalue(res, i, i_pronamespace),
											  finfo[i].oid);
		finfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
		finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
		finfo[i].prorettype = strdup(PQgetvalue(res, i, i_prorettype));
1939
		finfo[i].proacl = strdup(PQgetvalue(res, i, i_proacl));
1940 1941 1942
		finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
		if (finfo[i].nargs == 0)
			finfo[i].argtypes = NULL;
1943
		else
V
Vadim B. Mikheev 已提交
1944
		{
1945 1946 1947 1948 1949
			finfo[i].argtypes = malloc(finfo[i].nargs * sizeof(finfo[i].argtypes[0]));
			parseNumericArray(PQgetvalue(res, i, i_proargtypes),
							  finfo[i].argtypes,
							  finfo[i].nargs);
		}
1950

1951
		finfo[i].dumped = false;
1952

1953 1954 1955 1956
		if (strlen(finfo[i].usename) == 0)
			write_msg(NULL, "WARNING: owner of function \"%s\" appears to be invalid\n",
					  finfo[i].proname);
	}
1957

1958
	PQclear(res);
1959

1960
	destroyPQExpBuffer(query);
1961

1962 1963
	return finfo;
}
1964

1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
/*
 * getTables
 *	  read all the user-defined tables (no indexes, no catalogs)
 * in the system catalogs return them in the TableInfo* structure
 *
 * numTables is set to the number of tables read in
 */
TableInfo *
getTables(int *numTables)
{
	PGresult   *res;
	int			ntups;
	int			i;
	PQExpBuffer query = createPQExpBuffer();
	PQExpBuffer delqry = createPQExpBuffer();
	PQExpBuffer lockquery = createPQExpBuffer();
	TableInfo  *tblinfo;
1982

1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993
	int			i_reloid;
	int			i_relname;
	int			i_relnamespace;
	int			i_relkind;
	int			i_relacl;
	int			i_usename;
	int			i_relchecks;
	int			i_reltriggers;
	int			i_relhasindex;
	int			i_relhasrules;
	int			i_relhasoids;
1994

1995 1996
	/* Make sure we are in proper schema */
	selectSourceSchema("pg_catalog");
B
Bruce Momjian 已提交
1997

1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
	/*
	 * Find all the tables (including views and sequences).
	 *
	 * We include system catalogs, so that we can work if a user table
	 * is defined to inherit from a system catalog (pretty weird, but...)
	 *
	 * We ignore tables that are not type 'r' (ordinary relation) or 'S'
	 * (sequence) or 'v' (view).
	 *
	 * Note: in this phase we should collect only a minimal amount of
	 * information about each table, basically just enough to decide if
	 * it is interesting.
	 */
2011

2012 2013 2014 2015 2016
	if (g_fout->remoteVersion >= 70300)
	{
		appendPQExpBuffer(query,
						  "SELECT pg_class.oid, relname, relacl, relkind, "
						  "relnamespace, "
2017

2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075
						  "(select usename from pg_user where relowner = usesysid) as usename, "
						  "relchecks, reltriggers, "
						  "relhasindex, relhasrules, relhasoids "
						  "from pg_class "
						  "where relkind in ('%c', '%c', '%c') "
						  "order by oid",
						  RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
	}
	else if (g_fout->remoteVersion >= 70200)
	{
		appendPQExpBuffer(query,
						  "SELECT pg_class.oid, relname, relacl, relkind, "
						  "0::oid as relnamespace, "
						  "(select usename from pg_user where relowner = usesysid) as usename, "
						  "relchecks, reltriggers, "
						  "relhasindex, relhasrules, relhasoids "
						  "from pg_class "
						  "where relkind in ('%c', '%c', '%c') "
						  "order by oid",
					   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
	}
	else if (g_fout->remoteVersion >= 70100)
	{
		/* all tables have oids in 7.1 */
		appendPQExpBuffer(query,
						"SELECT pg_class.oid, relname, relacl, relkind, "
						  "0::oid as relnamespace, "
						  "(select usename from pg_user where relowner = usesysid) as usename, "
						  "relchecks, reltriggers, "
						  "relhasindex, relhasrules, 't'::bool as relhasoids "
						  "from pg_class "
						  "where relkind in ('%c', '%c', '%c') "
						  "order by oid",
					   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
	}
	else
	{
		/*
		 * Before 7.1, view relkind was not set to 'v', so we must check
		 * if we have a view by looking for a rule in pg_rewrite.
		 */
		appendPQExpBuffer(query,
						  "SELECT c.oid, relname, relacl, "
						  "CASE WHEN relhasrules and relkind = 'r' "
				  "  and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
				  "             r.ev_class = c.oid AND r.ev_type = '1') "
						  "THEN '%c'::\"char\" "
						  "ELSE relkind END AS relkind,"
						  "0::oid as relnamespace, "
						  "(select usename from pg_user where relowner = usesysid) as usename, "
						  "relchecks, reltriggers, "
						  "relhasindex, relhasrules, 't'::bool as relhasoids "
						  "from pg_class c "
						  "where relkind in ('%c', '%c') "
						  "order by oid",
						  RELKIND_VIEW,
						  RELKIND_RELATION, RELKIND_SEQUENCE);
	}
2076

2077 2078 2079 2080 2081 2082 2083 2084
	res = PQexec(g_conn, query->data);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		write_msg(NULL, "query to obtain list of tables failed: %s",
				  PQerrorMessage(g_conn));
		exit_nicely();
	}
2085

2086
	ntups = PQntuples(res);
2087

2088
	*numTables = ntups;
2089

2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100
	/*
	 * Extract data from result and lock dumpable tables.  We do the
	 * locking before anything else, to minimize the window wherein a
	 * table could disappear under us.
	 *
	 * Note that we have to save info about all tables here, even when
	 * dumping only one, because we don't yet know which tables might be
	 * inheritance ancestors of the target table.
	 */
	tblinfo = (TableInfo *) malloc(ntups * sizeof(TableInfo));
	memset(tblinfo, 0, ntups * sizeof(TableInfo));
2101

2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
	i_reloid = PQfnumber(res, "oid");
	i_relname = PQfnumber(res, "relname");
	i_relnamespace = PQfnumber(res, "relnamespace");
	i_relacl = PQfnumber(res, "relacl");
	i_relkind = PQfnumber(res, "relkind");
	i_usename = PQfnumber(res, "usename");
	i_relchecks = PQfnumber(res, "relchecks");
	i_reltriggers = PQfnumber(res, "reltriggers");
	i_relhasindex = PQfnumber(res, "relhasindex");
	i_relhasrules = PQfnumber(res, "relhasrules");
	i_relhasoids = PQfnumber(res, "relhasoids");
2113

2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127
	for (i = 0; i < ntups; i++)
	{
		tblinfo[i].oid = strdup(PQgetvalue(res, i, i_reloid));
		tblinfo[i].relname = strdup(PQgetvalue(res, i, i_relname));
		tblinfo[i].relnamespace = findNamespace(PQgetvalue(res, i, i_relnamespace),
												tblinfo[i].oid);
		tblinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
		tblinfo[i].relacl = strdup(PQgetvalue(res, i, i_relacl));
		tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
		tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
		tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
		tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
		tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
		tblinfo[i].ntrig = atoi(PQgetvalue(res, i, i_reltriggers));
2128

2129
		/* other fields were zeroed above */
B
Bruce,  
Bruce Momjian 已提交
2130

2131 2132 2133 2134 2135
		/*
		 * Decide whether we want to dump this table.
		 */
		selectDumpableTable(&tblinfo[i]);
		tblinfo[i].interesting = tblinfo[i].dump;
2136

2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
		/*
		 * Read-lock target tables to make sure they aren't DROPPED or
		 * altered in schema before we get around to dumping them.
		 *
		 * Note that we don't explicitly lock parents of the target tables;
		 * we assume our lock on the child is enough to prevent schema
		 * alterations to parent tables.
		 *
		 * NOTE: it'd be kinda nice to lock views and sequences too, not only
		 * plain tables, but the backend doesn't presently allow that.
		 */
		if (tblinfo[i].dump && tblinfo[i].relkind == RELKIND_RELATION)
		{
			PGresult   *lres;
B
Bruce,  
Bruce Momjian 已提交
2151

2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
			resetPQExpBuffer(lockquery);
			appendPQExpBuffer(lockquery,
							  "LOCK TABLE %s IN ACCESS SHARE MODE",
							  fmtQualifiedId(tblinfo[i].relnamespace->nspname,
											 tblinfo[i].relname));
			lres = PQexec(g_conn, lockquery->data);
			if (!lres || PQresultStatus(lres) != PGRES_COMMAND_OK)
			{
				write_msg(NULL, "Attempt to lock table \"%s\" failed.  %s",
						  tblinfo[i].relname, PQerrorMessage(g_conn));
				exit_nicely();
V
Vadim B. Mikheev 已提交
2163
			}
2164
			PQclear(lres);
V
Vadim B. Mikheev 已提交
2165
		}
2166

2167 2168 2169 2170
		/* Emit notice if join for owner failed */
		if (strlen(tblinfo[i].usename) == 0)
			write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
					  tblinfo[i].relname);
2171 2172
	}

2173
	PQclear(res);
2174 2175
	destroyPQExpBuffer(query);
	destroyPQExpBuffer(delqry);
2176
	destroyPQExpBuffer(lockquery);
2177

2178
	return tblinfo;
2179 2180 2181 2182
}

/*
 * getInherits
2183
 *	  read all the inheritance information
2184 2185
 * from the system catalogs return them in the InhInfo* structure
 *
2186
 * numInherits is set to the number of pairs read in
2187
 */
2188
InhInfo *
2189 2190
getInherits(int *numInherits)
{
2191
	PGresult   *res;
2192 2193
	int			ntups;
	int			i;
2194 2195
	PQExpBuffer query = createPQExpBuffer();
	InhInfo    *inhinfo;
2196

2197
	int			i_inhrelid;
2198
	int			i_inhparent;
2199

2200 2201 2202
	/* Make sure we are in proper schema */
	selectSourceSchema("pg_catalog");

2203 2204
	/* find all the inheritance information */

B
Hi, all  
Bruce Momjian 已提交
2205
	appendPQExpBuffer(query, "SELECT inhrelid, inhparent from pg_inherits");
2206

B
Hi, all  
Bruce Momjian 已提交
2207
	res = PQexec(g_conn, query->data);
2208 2209 2210
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
2211 2212
		write_msg(NULL, "query to obtain inheritance relationships failed: %s",
				  PQerrorMessage(g_conn));
2213
		exit_nicely();
2214 2215 2216 2217 2218 2219 2220 2221
	}

	ntups = PQntuples(res);

	*numInherits = ntups;

	inhinfo = (InhInfo *) malloc(ntups * sizeof(InhInfo));

2222
	i_inhrelid = PQfnumber(res, "inhrelid");
2223 2224 2225 2226
	i_inhparent = PQfnumber(res, "inhparent");

	for (i = 0; i < ntups; i++)
	{
2227
		inhinfo[i].inhrelid = strdup(PQgetvalue(res, i, i_inhrelid));
2228 2229 2230 2231
		inhinfo[i].inhparent = strdup(PQgetvalue(res, i, i_inhparent));
	}

	PQclear(res);
2232 2233 2234

	destroyPQExpBuffer(query);

2235
	return inhinfo;
2236 2237 2238 2239
}

/*
 * getTableAttrs -
2240
 *	  for each interesting table, read its attributes types and names
2241
 *
2242
 * this is implemented in a very inefficient way right now, looping
2243
 * through the tblinfo and doing a join per table to find the attrs and their
2244 2245
 * types
 *
2246
 *	modifies tblinfo
2247 2248
 */
void
2249
getTableAttrs(TableInfo *tblinfo, int numTables)
2250
{
2251 2252
	int			i,
				j;
2253
	PQExpBuffer q = createPQExpBuffer();
2254
	int			i_attname;
2255
	int			i_atttypname;
2256
	int			i_atttypmod;
2257
	int			i_attnotnull;
V
Vadim B. Mikheev 已提交
2258
	int			i_atthasdef;
2259
	PGresult   *res;
2260
	int			ntups;
2261
	bool		hasdefaults;
2262 2263 2264

	for (i = 0; i < numTables; i++)
	{
2265
		/* Don't bother to collect info for sequences */
2266
		if (tblinfo[i].relkind == RELKIND_SEQUENCE)
2267 2268
			continue;

2269 2270 2271 2272 2273 2274 2275 2276 2277 2278
		/* Don't bother with uninteresting tables, either */
		if (!tblinfo[i].interesting)
			continue;

		/*
		 * Make sure we are in proper schema for this table; this allows
		 * correct retrieval of formatted type names and default exprs
		 */
		selectSourceSchema(tblinfo[i].relnamespace->nspname);

2279 2280 2281
		/* find all the user attributes and their types */

		/*
2282
		 * we must read the attribute names in attribute number order!
2283
		 * because we will use the attnum to index into the attnames array
2284 2285 2286 2287
		 * later.  We actually ask to order by "attrelid, attnum" because
		 * (at least up to 7.3) the planner is not smart enough to realize
		 * it needn't re-sort the output of an indexscan on
		 * pg_attribute_relid_attnum_index.
2288 2289
		 */
		if (g_verbose)
2290 2291
			write_msg(NULL, "finding the columns and types for table %s\n",
					  tblinfo[i].relname);
2292

B
Hi, all  
Bruce Momjian 已提交
2293
		resetPQExpBuffer(q);
2294

2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306
		if (g_fout->remoteVersion >= 70300)
		{
			appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
							  "attnotnull, atthasdef, "
							  "pg_catalog.format_type(atttypid,atttypmod) as atttypname "
							  "from pg_catalog.pg_attribute a "
							  "where attrelid = '%s'::pg_catalog.oid "
							  "and attnum > 0::pg_catalog.int2 "
							  "order by attrelid, attnum",
							  tblinfo[i].oid);
		}
		else if (g_fout->remoteVersion >= 70100)
2307
		{
2308 2309 2310 2311 2312 2313 2314 2315
			appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
							  "attnotnull, atthasdef, "
							  "format_type(atttypid,atttypmod) as atttypname "
							  "from pg_attribute a "
							  "where attrelid = '%s'::oid "
							  "and attnum > 0::int2 "
							  "order by attrelid, attnum",
							  tblinfo[i].oid);
2316 2317 2318
		}
		else
		{
2319 2320 2321 2322 2323 2324 2325 2326
			/* format_type not available before 7.1 */
			appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
							  "attnotnull, atthasdef, "
							  "(select typname from pg_type where oid = atttypid) as atttypname "
							  "from pg_attribute a "
							  "where attrelid = '%s'::oid "
							  "and attnum > 0::int2 "
							  "order by attrelid, attnum",
2327
							  tblinfo[i].oid);
2328 2329
		}

B
Hi, all  
Bruce Momjian 已提交
2330
		res = PQexec(g_conn, q->data);
2331 2332 2333
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
2334
			write_msg(NULL, "query to get table columns failed: %s", PQerrorMessage(g_conn));
2335
			exit_nicely();
2336 2337 2338 2339 2340
		}

		ntups = PQntuples(res);

		i_attname = PQfnumber(res, "attname");
2341
		i_atttypname = PQfnumber(res, "atttypname");
2342
		i_atttypmod = PQfnumber(res, "atttypmod");
2343
		i_attnotnull = PQfnumber(res, "attnotnull");
V
Vadim B. Mikheev 已提交
2344
		i_atthasdef = PQfnumber(res, "atthasdef");
2345 2346 2347

		tblinfo[i].numatts = ntups;
		tblinfo[i].attnames = (char **) malloc(ntups * sizeof(char *));
2348
		tblinfo[i].atttypnames = (char **) malloc(ntups * sizeof(char *));
2349
		tblinfo[i].atttypmod = (int *) malloc(ntups * sizeof(int));
2350
		tblinfo[i].notnull = (bool *) malloc(ntups * sizeof(bool));
V
Vadim B. Mikheev 已提交
2351
		tblinfo[i].adef_expr = (char **) malloc(ntups * sizeof(char *));
2352 2353 2354 2355 2356
		tblinfo[i].inhAttrs = (bool *) malloc(ntups * sizeof(bool));
		tblinfo[i].inhAttrDef = (bool *) malloc(ntups * sizeof(bool));
		tblinfo[i].inhNotNull = (bool *) malloc(ntups * sizeof(bool));
		hasdefaults = false;

2357 2358 2359
		for (j = 0; j < ntups; j++)
		{
			tblinfo[i].attnames[j] = strdup(PQgetvalue(res, j, i_attname));
2360
			tblinfo[i].atttypnames[j] = strdup(PQgetvalue(res, j, i_atttypname));
2361
			tblinfo[i].atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
2362 2363
			tblinfo[i].notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
			tblinfo[i].adef_expr[j] = NULL;	/* fix below */
V
Vadim B. Mikheev 已提交
2364
			if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
2365 2366 2367 2368 2369 2370
				hasdefaults = true;
			/* these flags will be set in flagInhAttrs() */
			tblinfo[i].inhAttrs[j] = false;
			tblinfo[i].inhAttrDef[j] = false;
			tblinfo[i].inhNotNull[j] = false;
		}
2371

2372
		PQclear(res);
2373

2374 2375 2376 2377 2378 2379 2380 2381 2382
		if (hasdefaults)
		{
			int			numDefaults;

			if (g_verbose)
				write_msg(NULL, "finding DEFAULT expressions for table %s\n",
						  tblinfo[i].relname);

			resetPQExpBuffer(q);
2383 2384 2385 2386 2387 2388 2389 2390 2391
			if (g_fout->remoteVersion >= 70300)
			{
				appendPQExpBuffer(q, "SELECT adnum, "
								  "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
								  "FROM pg_catalog.pg_attrdef "
								  "WHERE adrelid = '%s'::pg_catalog.oid",
								  tblinfo[i].oid);
			}
			else if (g_fout->remoteVersion >= 70200)
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413
			{
				appendPQExpBuffer(q, "SELECT adnum, "
								  "pg_get_expr(adbin, adrelid) AS adsrc "
								  "FROM pg_attrdef "
								  "WHERE adrelid = '%s'::oid",
								  tblinfo[i].oid);
			}
			else
			{
				/* no pg_get_expr, so must rely on adsrc */
				appendPQExpBuffer(q, "SELECT adnum, adsrc FROM pg_attrdef "
								  "WHERE adrelid = '%s'::oid",
								  tblinfo[i].oid);
			}
			res = PQexec(g_conn, q->data);
			if (!res ||
				PQresultStatus(res) != PGRES_TUPLES_OK)
			{
				write_msg(NULL, "query to get column default values failed: %s",
						  PQerrorMessage(g_conn));
				exit_nicely();
			}
2414

2415 2416 2417 2418 2419 2420
			numDefaults = PQntuples(res);
			for (j = 0; j < numDefaults; j++)
			{
				int		adnum = atoi(PQgetvalue(res, j, 0));

				if (adnum <= 0 || adnum > ntups)
B
Bruce Momjian 已提交
2421
				{
2422 2423
					write_msg(NULL, "bogus adnum value %d for table %s\n",
							  adnum, tblinfo[i].relname);
2424
					exit_nicely();
2425
				}
2426
				tblinfo[i].adef_expr[adnum-1] = strdup(PQgetvalue(res, j, 1));
V
Vadim B. Mikheev 已提交
2427
			}
2428
			PQclear(res);
2429 2430
		}
	}
2431 2432

	destroyPQExpBuffer(q);
2433 2434 2435 2436
}


/*
2437
 * dumpComment --
B
Bruce,  
Bruce Momjian 已提交
2438
 *
2439
 * This routine is used to dump any comments associated with the
B
Bruce,  
Bruce Momjian 已提交
2440
 * oid handed to this routine. The routine takes a constant character
2441
 * string for the target part of the comment-creation command, plus
2442 2443
 * the namespace and owner of the object (for labeling the ArchiveEntry),
 * plus OID, class name, and subid which are the lookup key for pg_description.
2444 2445 2446 2447
 * If a matching pg_description entry is found, it is dumped.
 * Additional dependencies can be passed for the comment, too --- this is
 * needed for VIEWs, whose comments are filed under the table OID but
 * which are dumped in order by their rule OID.
2448
 */
B
Bruce,  
Bruce Momjian 已提交
2449

T
Tom Lane 已提交
2450
static void
2451 2452 2453
dumpComment(Archive *fout, const char *target,
			const char *namespace, const char *owner,
			const char *oid, const char *classname, int subid,
2454
			const char *((*deps)[]))
2455 2456
{
	PGresult   *res;
B
Bruce,  
Bruce Momjian 已提交
2457
	PQExpBuffer query;
2458
	int			i_description;
B
Bruce,  
Bruce Momjian 已提交
2459

2460 2461 2462 2463
	/* Comments are SCHEMA not data */
	if (dataOnly)
		return;

2464 2465 2466 2467 2468
	/*
	 * Note we do NOT change source schema here; preserve the caller's
	 * setting, instead.
	 */

B
Bruce,  
Bruce Momjian 已提交
2469 2470 2471
	/*** Build query to find comment ***/

	query = createPQExpBuffer();
2472

2473 2474 2475
	if (fout->remoteVersion >= 70300)
	{
		appendPQExpBuffer(query, "SELECT description FROM pg_catalog.pg_description "
2476 2477
						  "WHERE objoid = '%s'::pg_catalog.oid and classoid = "
						  "'pg_catalog.%s'::pg_catalog.regclass "
2478 2479 2480 2481
						  "and objsubid = %d",
						  oid, classname, subid);
	}
	else if (fout->remoteVersion >= 70200)
2482 2483
	{
		appendPQExpBuffer(query, "SELECT description FROM pg_description "
2484
						  "WHERE objoid = '%s'::oid and classoid = "
2485
					   "(SELECT oid FROM pg_class where relname = '%s') "
2486 2487 2488 2489 2490 2491
						  "and objsubid = %d",
						  oid, classname, subid);
	}
	else
	{
		/* Note: this will fail to find attribute comments in pre-7.2... */
2492
		appendPQExpBuffer(query, "SELECT description FROM pg_description WHERE objoid = '%s'::oid", oid);
2493
	}
B
Bruce,  
Bruce Momjian 已提交
2494 2495 2496 2497

	/*** Execute query ***/

	res = PQexec(g_conn, query->data);
2498 2499
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
2500
		write_msg(NULL, "query to get comment on oid %s failed: %s",
2501
				  oid, PQerrorMessage(g_conn));
2502
		exit_nicely();
B
Bruce,  
Bruce Momjian 已提交
2503 2504 2505 2506
	}

	/*** If a comment exists, build COMMENT ON statement ***/

2507
	if (PQntuples(res) == 1)
2508
	{
B
Bruce,  
Bruce Momjian 已提交
2509
		i_description = PQfnumber(res, "description");
B
Bruce Momjian 已提交
2510
		resetPQExpBuffer(query);
2511
		appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
2512 2513
		formatStringLiteral(query, PQgetvalue(res, 0, i_description),
							PASS_LFTAB);
2514
		appendPQExpBuffer(query, ";\n");
B
Bruce Momjian 已提交
2515

2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560
		ArchiveEntry(fout, oid, target, namespace, owner,
					 "COMMENT", deps,
					 query->data, "", NULL, NULL, NULL);
	}

	PQclear(res);
	destroyPQExpBuffer(query);
}

/*
 * dumpTableComment --
 *
 * As above, but dump comments for both the specified table (or view)
 * and its columns.  For speed, we want to do this with only one query.
 */
static void
dumpTableComment(Archive *fout, TableInfo *tbinfo,
				 const char *reltypename,
				 const char *((*deps)[]))
{
	PGresult   *res;
	PQExpBuffer query;
	PQExpBuffer target;
	int			i_description;
	int			i_objsubid;
	int			ntups;
	int			i;

	/* Comments are SCHEMA not data */
	if (dataOnly)
		return;

	/*
	 * Note we do NOT change source schema here; preserve the caller's
	 * setting, instead.
	 */

	/*** Build query to find comments ***/

	query = createPQExpBuffer();
	target = createPQExpBuffer();

	if (fout->remoteVersion >= 70300)
	{
		appendPQExpBuffer(query, "SELECT description, objsubid FROM pg_catalog.pg_description "
2561 2562
						  "WHERE objoid = '%s'::pg_catalog.oid and classoid = "
						  "'pg_catalog.pg_class'::pg_catalog.regclass "
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623
						  "ORDER BY objoid, classoid, objsubid",
						  tbinfo->oid);
	}
	else if (fout->remoteVersion >= 70200)
	{
		appendPQExpBuffer(query, "SELECT description, objsubid FROM pg_description "
						  "WHERE objoid = '%s'::oid and classoid = "
					   "(SELECT oid FROM pg_class where relname = 'pg_class') "
						  "ORDER BY objoid, classoid, objsubid",
						  tbinfo->oid);
	}
	else
	{
		/* Note: this will fail to find attribute comments in pre-7.2... */
		appendPQExpBuffer(query, "SELECT description, 0 as objsubid FROM pg_description WHERE objoid = '%s'::oid", tbinfo->oid);
	}

	/*** Execute query ***/

	res = PQexec(g_conn, query->data);
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		write_msg(NULL, "query to get comments on table %s failed: %s",
				  tbinfo->relname, PQerrorMessage(g_conn));
		exit_nicely();
	}
	i_description = PQfnumber(res, "description");
	i_objsubid = PQfnumber(res, "objsubid");

	/*** If comments exist, build COMMENT ON statements ***/

	ntups = PQntuples(res);
	for (i = 0; i < ntups; i++)
	{
		const char *descr = PQgetvalue(res, i, i_description);
		int objsubid = atoi(PQgetvalue(res, i, i_objsubid));

		if (objsubid == 0)
		{
			resetPQExpBuffer(target);
			appendPQExpBuffer(target, "%s %s", reltypename,
							  fmtId(tbinfo->relname, force_quotes));

			resetPQExpBuffer(query);
			appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
			formatStringLiteral(query, descr, PASS_LFTAB);
			appendPQExpBuffer(query, ";\n");

			ArchiveEntry(fout, tbinfo->oid, target->data,
						 tbinfo->relnamespace->nspname, tbinfo->usename,
						 "COMMENT", deps,
						 query->data, "", NULL, NULL, NULL);
		}
		else if (objsubid > 0 && objsubid <= tbinfo->numatts)
		{
			resetPQExpBuffer(target);
			appendPQExpBuffer(target, "COLUMN %s.",
							  fmtId(tbinfo->relname, force_quotes));
			appendPQExpBuffer(target, "%s",
							  fmtId(tbinfo->attnames[objsubid-1],
									force_quotes));
B
Bruce,  
Bruce Momjian 已提交
2624

2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635
			resetPQExpBuffer(query);
			appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
			formatStringLiteral(query, descr, PASS_LFTAB);
			appendPQExpBuffer(query, ";\n");

			ArchiveEntry(fout, tbinfo->oid, target->data,
						 tbinfo->relnamespace->nspname, tbinfo->usename,
						 "COMMENT", deps,
						 query->data, "", NULL, NULL, NULL);
		}
	}
B
Bruce,  
Bruce Momjian 已提交
2636 2637

	PQclear(res);
2638
	destroyPQExpBuffer(query);
2639
	destroyPQExpBuffer(target);
B
Bruce,  
Bruce Momjian 已提交
2640 2641
}

2642
/*
2643
 * dumpDBComment --
B
Bruce,  
Bruce Momjian 已提交
2644
 *
2645
 * This routine is used to dump any comments associated with the
2646
 * database to which we are currently connected.
2647
 */
2648
void
B
Bruce Momjian 已提交
2649
dumpDBComment(Archive *fout)
2650 2651
{
	PGresult   *res;
B
Bruce,  
Bruce Momjian 已提交
2652
	PQExpBuffer query;
2653
	int			i_oid;
B
Bruce,  
Bruce Momjian 已提交
2654

2655 2656 2657
	/* Make sure we are in proper schema */
	selectSourceSchema("pg_catalog");

B
Bruce,  
Bruce Momjian 已提交
2658 2659 2660
	/*** Build query to find comment ***/

	query = createPQExpBuffer();
2661
	appendPQExpBuffer(query, "SELECT oid FROM pg_database WHERE datname = ");
2662
	formatStringLiteral(query, PQdb(g_conn), CONV_ALL);
B
Bruce,  
Bruce Momjian 已提交
2663 2664 2665 2666

	/*** Execute query ***/

	res = PQexec(g_conn, query->data);
2667 2668
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
2669
		write_msg(NULL, "query to get database oid failed: %s",
2670
				  PQerrorMessage(g_conn));
2671
		exit_nicely();
B
Bruce,  
Bruce Momjian 已提交
2672 2673 2674 2675
	}

	/*** If a comment exists, build COMMENT ON statement ***/

2676 2677
	if (PQntuples(res) != 0)
	{
B
Bruce,  
Bruce Momjian 已提交
2678 2679 2680
		i_oid = PQfnumber(res, "oid");
		resetPQExpBuffer(query);
		appendPQExpBuffer(query, "DATABASE %s", fmtId(PQdb(g_conn), force_quotes));
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698
		dumpComment(fout, query->data, NULL, "",
					PQgetvalue(res, 0, i_oid), "pg_database", 0, NULL);
	}

	PQclear(res);
	destroyPQExpBuffer(query);
}

/*
 * dumpNamespaces
 *    writes out to fout the queries to recreate user-defined namespaces
 */
void
dumpNamespaces(Archive *fout, NamespaceInfo *nsinfo, int numNamespaces)
{
	PQExpBuffer q = createPQExpBuffer();
	PQExpBuffer delq = createPQExpBuffer();
	int			i;
2699
	char	   *qnspname;
2700 2701 2702

	for (i = 0; i < numNamespaces; i++)
	{
2703 2704
		NamespaceInfo *nspinfo = &nsinfo[i];

2705
		/* skip if not to be dumped */
2706
		if (!nspinfo->dump)
2707 2708 2709
			continue;

		/* don't dump dummy namespace from pre-7.3 source */
2710
		if (strlen(nspinfo->nspname) == 0)
2711 2712
			continue;

2713
		qnspname = strdup(fmtId(nspinfo->nspname, force_quotes));
2714

2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
		/*
		 * If it's the PUBLIC namespace, don't emit a CREATE SCHEMA
		 * record for it, since we expect PUBLIC to exist already in
		 * the destination database.  And emit ACL info only if the ACL
		 * isn't the standard value for PUBLIC.
		 */
		if (strcmp(nspinfo->nspname, "public") == 0)
		{
			if (!aclsSkip && strcmp(nspinfo->nspacl, "{=UC}") != 0)
				dumpACL(fout, "SCHEMA", qnspname, NULL,
						nspinfo->usename, nspinfo->nspacl,
						nspinfo->oid);
		}
		else
		{
			resetPQExpBuffer(q);
			resetPQExpBuffer(delq);
2732

2733
			appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
2734

2735
			appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
2736

2737 2738 2739 2740
			ArchiveEntry(fout, nspinfo->oid, nspinfo->nspname,
						 NULL,
						 nspinfo->usename, "SCHEMA", NULL,
						 q->data, delq->data, NULL, NULL, NULL);
2741

2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
			/*** Dump Schema Comments ***/
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "SCHEMA %s", qnspname);
			dumpComment(fout, q->data,
						NULL, nspinfo->usename,
						nspinfo->oid, "pg_namespace", 0, NULL);

			if (!aclsSkip)
				dumpACL(fout, "SCHEMA", qnspname, NULL,
						nspinfo->usename, nspinfo->nspacl,
						nspinfo->oid);
		}

		free(qnspname);
2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801
	}

	destroyPQExpBuffer(q);
	destroyPQExpBuffer(delq);
}

/*
 * dumpOneBaseType
 *    writes out to fout the queries to recreate a user-defined base type
 *    as requested by dumpTypes
 */
static void
dumpOneBaseType(Archive *fout, TypeInfo *tinfo,
				FuncInfo *g_finfo, int numFuncs,
				TypeInfo *g_tinfo, int numTypes)
{
	PQExpBuffer q = createPQExpBuffer();
	PQExpBuffer delq = createPQExpBuffer();
	PQExpBuffer query = createPQExpBuffer();
	PGresult   *res;
	int			ntups;
	int			funcInd;
	char	   *typlen;
	char	   *typprtlen;
	char	   *typinput;
	char	   *typoutput;
	char	   *typreceive;
	char	   *typsend;
	char	   *typinputoid;
	char	   *typoutputoid;
	char	   *typreceiveoid;
	char	   *typsendoid;
	char	   *typdelim;
	char	   *typdefault;
	char	   *typbyval;
	char	   *typalign;
	char	   *typstorage;
	const char *((*deps)[]);
	int			depIdx = 0;

	deps = malloc(sizeof(char *) * 10);

	/* Set proper schema search path so regproc references list correctly */
	selectSourceSchema(tinfo->typnamespace->nspname);

	/* Fetch type-specific details */
2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816
	if (fout->remoteVersion >= 70300)
	{
		appendPQExpBuffer(query, "SELECT typlen, typprtlen, "
						  "typinput, typoutput, typreceive, typsend, "
						  "typinput::pg_catalog.oid as typinputoid, "
						  "typoutput::pg_catalog.oid as typoutputoid, "
						  "typreceive::pg_catalog.oid as typreceiveoid, "
						  "typsend::pg_catalog.oid as typsendoid, "
						  "typdelim, typdefault, typbyval, typalign, "
						  "typstorage "
						  "FROM pg_catalog.pg_type "
						  "WHERE oid = '%s'::pg_catalog.oid",
						  tinfo->oid);
	}
	else if (fout->remoteVersion >= 70100)
2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876
	{
		appendPQExpBuffer(query, "SELECT typlen, typprtlen, "
						  "typinput, typoutput, typreceive, typsend, "
						  "typinput::oid as typinputoid, "
						  "typoutput::oid as typoutputoid, "
						  "typreceive::oid as typreceiveoid, "
						  "typsend::oid as typsendoid, "
						  "typdelim, typdefault, typbyval, typalign, "
						  "typstorage "
						  "FROM pg_type "
						  "WHERE oid = '%s'::oid",
						  tinfo->oid);
	}
	else
	{
		appendPQExpBuffer(query, "SELECT typlen, typprtlen, "
						  "typinput, typoutput, typreceive, typsend, "
						  "typinput::oid as typinputoid, "
						  "typoutput::oid as typoutputoid, "
						  "typreceive::oid as typreceiveoid, "
						  "typsend::oid as typsendoid, "
						  "typdelim, typdefault, typbyval, typalign, "
						  "'p'::char as typstorage "
						  "FROM pg_type "
						  "WHERE oid = '%s'::oid",
						  tinfo->oid);
	}

	res = PQexec(g_conn, query->data);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		write_msg(NULL, "query to obtain type information for %s failed: %s",
				  tinfo->typname, PQerrorMessage(g_conn));
		exit_nicely();
	}

	/* Expecting a single result only */
	ntups = PQntuples(res);
	if (ntups != 1)
	{
		write_msg(NULL, "Got %d rows instead of one from: %s",
				  ntups, query->data);
		exit_nicely();
	}

	typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
	typprtlen = PQgetvalue(res, 0, PQfnumber(res, "typprtlen"));
	typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
	typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
	typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
	typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
	typinputoid = PQgetvalue(res, 0, PQfnumber(res, "typinputoid"));
	typoutputoid = PQgetvalue(res, 0, PQfnumber(res, "typoutputoid"));
	typreceiveoid = PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid"));
	typsendoid = PQgetvalue(res, 0, PQfnumber(res, "typsendoid"));
	typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
	if (PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
		typdefault = NULL;
	else
2877
		typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909
	typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
	typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
	typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));

	/*
	 * Before we create a type, we need to create the input and output
	 * functions for it, if they haven't been created already.  So make
	 * sure there are dependency entries for this.  But don't include
	 * dependencies if the functions aren't going to be dumped.
	 */
	funcInd = findFuncByOid(g_finfo, numFuncs, typinputoid);
	if (funcInd >= 0 && g_finfo[funcInd].pronamespace->dump)
		(*deps)[depIdx++] = strdup(typinputoid);

	funcInd = findFuncByOid(g_finfo, numFuncs, typoutputoid);
	if (funcInd >= 0 && g_finfo[funcInd].pronamespace->dump)
		(*deps)[depIdx++] = strdup(typoutputoid);

	if (strcmp(typreceiveoid, typinputoid) != 0)
	{
		funcInd = findFuncByOid(g_finfo, numFuncs, typreceiveoid);
		if (funcInd >= 0 && g_finfo[funcInd].pronamespace->dump)
			(*deps)[depIdx++] = strdup(typreceiveoid);
	}

	if (strcmp(typsendoid, typoutputoid) != 0)
	{
		funcInd = findFuncByOid(g_finfo, numFuncs, typsendoid);
		if (funcInd >= 0 && g_finfo[funcInd].pronamespace->dump)
			(*deps)[depIdx++] = strdup(typsendoid);
	}

2910 2911 2912 2913
	/* DROP must be fully qualified in case same name appears in pg_catalog */
	appendPQExpBuffer(delq, "DROP TYPE %s.",
					  fmtId(tinfo->typnamespace->nspname, force_quotes));
	appendPQExpBuffer(delq, "%s;\n",
2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941
					  fmtId(tinfo->typname, force_quotes));

	appendPQExpBuffer(q,
					  "CREATE TYPE %s "
					  "( internallength = %s, externallength = %s,",
					  fmtId(tinfo->typname, force_quotes),
					  (strcmp(typlen, "-1") == 0) ? "variable" : typlen,
					  (strcmp(typprtlen, "-1") == 0) ? "variable" : typprtlen);

	if (fout->remoteVersion >= 70300)
	{
		/* regproc result is correctly quoted in 7.3 */
		appendPQExpBuffer(q, " input = %s, output = %s, "
						  "send = %s, receive = %s",
						  typinput, typoutput, typsend, typreceive);
	}
	else
	{
		/* regproc delivers an unquoted name before 7.3 */
		/* cannot combine these because fmtId uses static result area */
		appendPQExpBuffer(q, " input = %s,",
						  fmtId(typinput, force_quotes));
		appendPQExpBuffer(q, " output = %s,",
						  fmtId(typoutput, force_quotes));
		appendPQExpBuffer(q, " send = %s,",
						  fmtId(typsend, force_quotes));
		appendPQExpBuffer(q, " receive = %s",
						  fmtId(typreceive, force_quotes));
B
Bruce,  
Bruce Momjian 已提交
2942 2943
	}

2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000
	if (typdefault != NULL)
	{
		appendPQExpBuffer(q, ", default = ");
		formatStringLiteral(q, typdefault, CONV_ALL);
	}

	if (tinfo->isArray)
	{
		char	   *elemType;

		/* reselect schema in case changed by function dump */
		selectSourceSchema(tinfo->typnamespace->nspname);
		elemType = getFormattedTypeName(tinfo->typelem, zeroAsOpaque);
		appendPQExpBuffer(q, ", element = %s, delimiter = ", elemType);
		formatStringLiteral(q, typdelim, CONV_ALL);
		free(elemType);

		(*deps)[depIdx++] = strdup(tinfo->typelem);
	}

	if (strcmp(typalign, "c") == 0)
		appendPQExpBuffer(q, ", alignment = char");
	else if (strcmp(typalign, "s") == 0)
		appendPQExpBuffer(q, ", alignment = int2");
	else if (strcmp(typalign, "i") == 0)
		appendPQExpBuffer(q, ", alignment = int4");
	else if (strcmp(typalign, "d") == 0)
		appendPQExpBuffer(q, ", alignment = double");

	if (strcmp(typstorage, "p") == 0)
		appendPQExpBuffer(q, ", storage = plain");
	else if (strcmp(typstorage, "e") == 0)
		appendPQExpBuffer(q, ", storage = external");
	else if (strcmp(typstorage, "x") == 0)
		appendPQExpBuffer(q, ", storage = extended");
	else if (strcmp(typstorage, "m") == 0)
		appendPQExpBuffer(q, ", storage = main");

	if (strcmp(typbyval, "t") == 0)
		appendPQExpBuffer(q, ", passedbyvalue);\n");
	else
		appendPQExpBuffer(q, ");\n");

	(*deps)[depIdx++] = NULL;		/* End of List */

	ArchiveEntry(fout, tinfo->oid, tinfo->typname,
				 tinfo->typnamespace->nspname,
				 tinfo->usename, "TYPE", deps,
				 q->data, delq->data, NULL, NULL, NULL);

	/*** Dump Type Comments ***/
	resetPQExpBuffer(q);

	appendPQExpBuffer(q, "TYPE %s", fmtId(tinfo->typname, force_quotes));
	dumpComment(fout, q->data,
				tinfo->typnamespace->nspname, tinfo->usename,
				tinfo->oid, "pg_type", 0, NULL);
B
Bruce,  
Bruce Momjian 已提交
3001 3002

	PQclear(res);
3003 3004
	destroyPQExpBuffer(q);
	destroyPQExpBuffer(delq);
3005
	destroyPQExpBuffer(query);
B
Bruce,  
Bruce Momjian 已提交
3006 3007
}

3008 3009
/*
 * dumpOneDomain
3010
 *    writes out to fout the queries to recreate a user-defined domain
3011 3012
 *    as requested by dumpTypes
 */
3013
static void
3014 3015 3016 3017 3018
dumpOneDomain(Archive *fout, TypeInfo *tinfo)
{
	PQExpBuffer q = createPQExpBuffer();
	PQExpBuffer delq = createPQExpBuffer();
	PQExpBuffer query = createPQExpBuffer();
3019
	PGresult   *res;
3020
	int			ntups;
3021 3022 3023 3024
	char	   *typnotnull;
	char	   *typdefn;
	char	   *typdefault;
	char	   *typbasetype;
3025 3026 3027 3028 3029
	const char *((*deps)[]);
	int			depIdx = 0;

	deps = malloc(sizeof(char *) * 10);

3030 3031 3032
	/* Set proper schema search path so type references list correctly */
	selectSourceSchema(tinfo->typnamespace->nspname);

3033
	/* Fetch domain specific details */
3034
	/* We assume here that remoteVersion must be at least 70300 */
3035
	appendPQExpBuffer(query, "SELECT typnotnull, "
3036
					  "pg_catalog.format_type(typbasetype, typtypmod) as typdefn, "
3037
					  "typdefault, typbasetype "
3038 3039
					  "FROM pg_catalog.pg_type "
					  "WHERE oid = '%s'::pg_catalog.oid",
3040
					  tinfo->oid);
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052

	res = PQexec(g_conn, query->data);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		write_msg(NULL, "query to obtain domain information failed: %s", PQerrorMessage(g_conn));
		exit_nicely();
	}

	/* Expecting a single result only */
	ntups = PQntuples(res);
	if (ntups != 1)
3053 3054 3055 3056 3057
	{
		write_msg(NULL, "Got %d rows instead of one from: %s",
				  ntups, query->data);
		exit_nicely();
	}
3058

3059 3060 3061 3062 3063
	typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
	typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
	if (PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
		typdefault = NULL;
	else
3064
		typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
3065
	typbasetype = PQgetvalue(res, 0, PQfnumber(res, "typbasetype"));
3066

3067 3068 3069 3070
	/* DROP must be fully qualified in case same name appears in pg_catalog */
	appendPQExpBuffer(delq, "DROP DOMAIN %s.",
					  fmtId(tinfo->typnamespace->nspname, force_quotes));
	appendPQExpBuffer(delq, "%s RESTRICT;\n",
3071
					  fmtId(tinfo->typname, force_quotes));
3072 3073 3074 3075

	appendPQExpBuffer(q,
					  "CREATE DOMAIN %s AS %s",
					  fmtId(tinfo->typname, force_quotes),
3076
					  typdefn);
3077 3078

	/* Depends on the base type */
3079
	(*deps)[depIdx++] = strdup(typbasetype);
3080

3081
	if (typnotnull[0] == 't')
3082 3083
		appendPQExpBuffer(q, " NOT NULL");

3084
	if (typdefault)
3085
		appendPQExpBuffer(q, " DEFAULT %s", typdefault);
3086 3087 3088 3089 3090

	appendPQExpBuffer(q, ";\n");

	(*deps)[depIdx++] = NULL;		/* End of List */

3091 3092 3093 3094
	ArchiveEntry(fout, tinfo->oid, tinfo->typname,
				 tinfo->typnamespace->nspname,
				 tinfo->usename, "DOMAIN", deps,
				 q->data, delq->data, NULL, NULL, NULL);
3095 3096 3097 3098 3099

	/*** Dump Domain Comments ***/
	resetPQExpBuffer(q);

	appendPQExpBuffer(q, "DOMAIN %s", fmtId(tinfo->typname, force_quotes));
3100 3101 3102 3103 3104 3105 3106 3107
	dumpComment(fout, q->data,
				tinfo->typnamespace->nspname, tinfo->usename,
				tinfo->oid, "pg_type", 0, NULL);

	PQclear(res);
	destroyPQExpBuffer(q);
	destroyPQExpBuffer(delq);
	destroyPQExpBuffer(query);
3108 3109
}

3110 3111
/*
 * dumpTypes
3112
 *	  writes out to fout the queries to recreate all the user-defined types
3113 3114
 */
void
B
Bruce Momjian 已提交
3115
dumpTypes(Archive *fout, FuncInfo *finfo, int numFuncs,
3116
		  TypeInfo *tinfo, int numTypes)
3117
{
3118
	int			i;
3119 3120 3121

	for (i = 0; i < numTypes; i++)
	{
3122 3123
		/* Dump only types in dumpable namespaces */
		if (!tinfo[i].typnamespace->dump)
3124 3125 3126
			continue;

		/* skip relation types */
3127
		if (atooid(tinfo[i].typrelid) != 0)
3128 3129
			continue;

3130 3131 3132 3133
		/* skip undefined placeholder types */
		if (!tinfo[i].isDefined)
			continue;

3134 3135
		/* skip all array types that start w/ underscore */
		if ((tinfo[i].typname[0] == '_') &&
3136
			atooid(tinfo[i].typelem) != 0)
3137 3138
			continue;

3139 3140 3141 3142 3143
		/* Dump out in proper style */
		if (tinfo[i].typtype == 'b')
			dumpOneBaseType(fout, &tinfo[i],
							finfo, numFuncs, tinfo, numTypes);
		else if (tinfo[i].typtype == 'd')
3144
			dumpOneDomain(fout, &tinfo[i]);
3145
	}
3146 3147
}

3148 3149
/*
 * dumpProcLangs
B
Bruce Momjian 已提交
3150
 *		  writes out to fout the queries to recreate user-defined procedural languages
3151 3152
 */
void
3153
dumpProcLangs(Archive *fout, FuncInfo finfo[], int numFuncs)
3154
{
3155 3156
	PGresult   *res;
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
3157 3158
	PQExpBuffer defqry = createPQExpBuffer();
	PQExpBuffer delqry = createPQExpBuffer();
3159
	int			ntups;
B
Bruce Momjian 已提交
3160
	int			i_oid;
3161 3162 3163
	int			i_lanname;
	int			i_lanpltrusted;
	int			i_lanplcallfoid;
3164
	int			i_lanvalidator = -1;
3165
	int			i_lancompiler;
3166
	int			i_lanacl = -1;
3167
	char	   *lanoid;
3168 3169
	char	   *lanname;
	char	   *lancompiler;
3170
	char	   *lanacl;
3171
	const char *lanplcallfoid;
3172
	const char *lanvalidator;
3173 3174
	const char *((*deps)[]);
	int			depIdx;
3175
	int			i,
3176 3177
				fidx,
				vidx = -1;
3178

3179 3180 3181
	/* Make sure we are in proper schema */
	selectSourceSchema("pg_catalog");

B
Bruce Momjian 已提交
3182
	appendPQExpBuffer(query, "SELECT oid, * FROM pg_language "
3183 3184
					  "WHERE lanispl "
					  "ORDER BY oid");
B
Hi, all  
Bruce Momjian 已提交
3185
	res = PQexec(g_conn, query->data);
3186 3187 3188
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
3189
		write_msg(NULL, "query to obtain list of procedural languages failed: %s",
3190
				  PQerrorMessage(g_conn));
3191
		exit_nicely();
3192 3193 3194
	}
	ntups = PQntuples(res);

B
Bruce Momjian 已提交
3195 3196 3197 3198
	i_lanname = PQfnumber(res, "lanname");
	i_lanpltrusted = PQfnumber(res, "lanpltrusted");
	i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
	i_lancompiler = PQfnumber(res, "lancompiler");
B
Bruce Momjian 已提交
3199
	i_oid = PQfnumber(res, "oid");
3200
	if (fout->remoteVersion >= 70300)
3201 3202
	{
		i_lanvalidator = PQfnumber(res, "lanvalidator");
3203
		i_lanacl = PQfnumber(res, "lanacl");
3204
	}
3205

B
Bruce Momjian 已提交
3206 3207
	for (i = 0; i < ntups; i++)
	{
3208
		lanoid = PQgetvalue(res, i, i_oid);
3209
		lanplcallfoid = PQgetvalue(res, i, i_lanplcallfoid);
3210 3211
		lanname = PQgetvalue(res, i, i_lanname);
		lancompiler = PQgetvalue(res, i, i_lancompiler);
3212
		if (fout->remoteVersion >= 70300)
3213 3214
		{
			lanvalidator = PQgetvalue(res, i, i_lanvalidator);
3215
			lanacl = PQgetvalue(res, i, i_lanacl);
3216
		}
3217
		else
3218 3219 3220 3221
		{
			lanvalidator = "0";
			lanacl = "{=U}";
		}
3222

3223 3224
		fidx = findFuncByOid(finfo, numFuncs, lanplcallfoid);
		if (fidx < 0)
3225
		{
3226
			write_msg(NULL, "handler procedure for procedural language %s not found\n",
3227
					  lanname);
3228
			exit_nicely();
3229 3230
		}

3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241
		if (strcmp(lanvalidator, "0") != 0)
		{
			vidx = findFuncByOid(finfo, numFuncs, lanvalidator);
			if (vidx < 0)
			{
				write_msg(NULL, "validator procedure for procedural language %s not found\n",
						  lanname);
				exit_nicely();
			}
		}

3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254
		/*
		 * Current theory is to dump PLs iff their underlying functions
		 * will be dumped (are in a dumpable namespace, or have a non-system
		 * OID in pre-7.3 databases).  Actually, we treat the PL itself
		 * as being in the underlying function's namespace, though it
		 * isn't really.  This avoids searchpath problems for the HANDLER
		 * clause.
		 */
		if (!finfo[fidx].pronamespace->dump)
			continue;

		resetPQExpBuffer(defqry);
		resetPQExpBuffer(delqry);
3255

3256
		/* Make a dependency to ensure function is dumped first */
3257
		deps = malloc(sizeof(char *) * (2 + (strcmp(lanvalidator, "0")!=0) ? 1 : 0));
3258 3259 3260
		depIdx = 0;

		(*deps)[depIdx++] = strdup(lanplcallfoid);
3261

3262 3263
		appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
						  fmtId(lanname, force_quotes));
3264

3265
		appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
3266
						  (PQgetvalue(res, i, i_lanpltrusted)[0] == 't') ?
3267 3268
						  "TRUSTED " : "",
						  fmtId(lanname, force_quotes));
3269
		appendPQExpBuffer(defqry, " HANDLER %s",
3270
						  fmtId(finfo[fidx].proname, force_quotes));
3271 3272
		if (strcmp(lanvalidator, "0")!=0)
		{
3273 3274 3275 3276 3277 3278 3279
			appendPQExpBuffer(defqry, " VALIDATOR ");
			/* Cope with possibility that validator is in different schema */
			if (finfo[vidx].pronamespace != finfo[fidx].pronamespace)
				appendPQExpBuffer(defqry, "%s.",
								  fmtId(finfo[vidx].pronamespace->nspname,
										force_quotes));
			appendPQExpBuffer(defqry, "%s",
3280 3281 3282 3283
							  fmtId(finfo[vidx].proname, force_quotes));
			(*deps)[depIdx++] = strdup(lanvalidator);
		}
		appendPQExpBuffer(defqry, ";\n");
3284

3285
		(*deps)[depIdx++] = NULL;		/* End of List */
B
Bruce Momjian 已提交
3286

3287 3288 3289 3290
		ArchiveEntry(fout, lanoid, lanname,
					 finfo[fidx].pronamespace->nspname, "",
					 "PROCEDURAL LANGUAGE", deps,
					 defqry->data, delqry->data, NULL, NULL, NULL);
3291 3292 3293 3294 3295 3296 3297 3298

		if (!aclsSkip)
		{
			char * tmp = strdup(fmtId(lanname, force_quotes));
			dumpACL(fout, "LANGUAGE", tmp, finfo[fidx].pronamespace->nspname,
					NULL, lanacl, lanoid);
			free(tmp);
		}
3299 3300 3301 3302
	}

	PQclear(res);

3303 3304 3305
	destroyPQExpBuffer(query);
	destroyPQExpBuffer(defqry);
	destroyPQExpBuffer(delqry);
3306 3307
}

3308 3309
/*
 * dumpFuncs
3310
 *	  writes out to fout the queries to recreate all the user-defined functions
3311 3312
 */
void
3313
dumpFuncs(Archive *fout, FuncInfo finfo[], int numFuncs)
3314
{
3315
	int			i;
3316 3317

	for (i = 0; i < numFuncs; i++)
3318 3319 3320 3321 3322 3323
	{
		/* Dump only funcs in dumpable namespaces */
		if (!finfo[i].pronamespace->dump)
			continue;

		dumpOneFunc(fout, &finfo[i]);
3324 3325
		if (!aclsSkip)
			dumpFuncACL(fout, &finfo[i]);
3326
	}
3327 3328
}

3329 3330 3331 3332 3333 3334
/*
 * format_function_signature: generate function name and argument list
 *
 * The argument type names are qualified if needed.  The function name
 * is never qualified.
 */
3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369
static char *
format_function_signature(FuncInfo *finfo)
{
	PQExpBufferData fn;
	int			j;

	initPQExpBuffer(&fn);
	appendPQExpBuffer(&fn, "%s (", fmtId(finfo->proname, force_quotes));
	for (j = 0; j < finfo->nargs; j++)
	{
		char	   *typname;

		typname = getFormattedTypeName(finfo->argtypes[j], zeroAsOpaque);
		appendPQExpBuffer(&fn, "%s%s",
						  (j > 0) ? "," : "",
						  typname);
		free(typname);
	}
	appendPQExpBuffer(&fn, ")");
	return fn.data;
}


static void
dumpFuncACL(Archive *fout, FuncInfo *finfo)
{
	char *funcsig;

	funcsig = format_function_signature(finfo);
	dumpACL(fout, "FUNCTION", funcsig, finfo->pronamespace->nspname,
			finfo->usename, finfo->proacl, finfo->oid);
	free(funcsig);
}


3370 3371
/*
 * dumpOneFunc:
3372
 *	  dump out only one function
3373
 */
3374
static void
3375
dumpOneFunc(Archive *fout, FuncInfo *finfo)
3376
{
3377
	PQExpBuffer query = createPQExpBuffer();
3378
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3379
	PQExpBuffer delqry = createPQExpBuffer();
3380
	PQExpBuffer asPart = createPQExpBuffer();
3381
	PGresult   *res = NULL;
3382
	char	   *funcsig = NULL;
3383 3384 3385 3386 3387 3388 3389
	int			ntups;
	char	   *proretset;
	char	   *prosrc;
	char	   *probin;
	char	   *provolatile;
	char	   *proimplicit;
	char	   *proisstrict;
3390
	char	   *prosecdef;
3391
	char	   *lanname;
B
Bruce Momjian 已提交
3392
	char	   *rettypename;
3393

3394
	if (finfo->dumped)
3395 3396
		goto done;

3397
	finfo->dumped = true;
3398

3399 3400 3401 3402 3403 3404 3405 3406
	/* Set proper schema search path so type references list correctly */
	selectSourceSchema(finfo->pronamespace->nspname);

	/* Fetch function-specific details */
	if (g_fout->remoteVersion >= 70300)
	{
		appendPQExpBuffer(query,
						  "SELECT proretset, prosrc, probin, "
3407
						  "provolatile, proimplicit, proisstrict, prosecdef, "
3408 3409 3410
						  "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) as lanname "
						  "FROM pg_catalog.pg_proc "
						  "WHERE oid = '%s'::pg_catalog.oid",
3411 3412 3413 3414 3415 3416 3417 3418 3419
						  finfo->oid);
	}
	else if (g_fout->remoteVersion >= 70100)
	{
		appendPQExpBuffer(query,
						  "SELECT proretset, prosrc, probin, "
						  "case when proiscachable then 'i' else 'v' end as provolatile, "
						  "'f'::boolean as proimplicit, "
						  "proisstrict, "
3420
						  "'f'::boolean as prosecdef, "
3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432
						  "(SELECT lanname FROM pg_language WHERE oid = prolang) as lanname "
						  "FROM pg_proc "
						  "WHERE oid = '%s'::oid",
						  finfo->oid);
	}
	else
	{
		appendPQExpBuffer(query,
						  "SELECT proretset, prosrc, probin, "
						  "case when proiscachable then 'i' else 'v' end as provolatile, "
						  "'f'::boolean as proimplicit, "
						  "'f'::boolean as proisstrict, "
3433
						  "'f'::boolean as prosecdef, "
3434 3435 3436 3437 3438
						  "(SELECT lanname FROM pg_language WHERE oid = prolang) as lanname "
						  "FROM pg_proc "
						  "WHERE oid = '%s'::oid",
						  finfo->oid);
	}
3439

3440
	res = PQexec(g_conn, query->data);
3441 3442
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
B
Bruce Momjian 已提交
3443
	{
3444 3445
		write_msg(NULL, "query to obtain function information for %s failed: %s",
				  finfo->proname, PQerrorMessage(g_conn));
3446
		exit_nicely();
B
Bruce Momjian 已提交
3447
	}
3448

3449 3450 3451
	/* Expecting a single result only */
	ntups = PQntuples(res);
	if (ntups != 1)
B
Bruce Momjian 已提交
3452
	{
3453 3454
		write_msg(NULL, "Got %d rows instead of one from: %s",
				  ntups, query->data);
3455
		exit_nicely();
B
Bruce Momjian 已提交
3456 3457
	}

3458 3459 3460 3461 3462 3463
	proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
	prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
	probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
	provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
	proimplicit = PQgetvalue(res, 0, PQfnumber(res, "proimplicit"));
	proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
3464
	prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
3465
	lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
3466

3467
	/*
B
Bruce Momjian 已提交
3468 3469
	 * See backend/commands/define.c for details of how the 'AS' clause is
	 * used.
3470
	 */
3471
	if (strcmp(probin, "-") != 0)
3472
	{
3473
		appendPQExpBuffer(asPart, "AS ");
3474 3475
		formatStringLiteral(asPart, probin, CONV_ALL);
		if (strcmp(prosrc, "-") != 0)
3476 3477
		{
			appendPQExpBuffer(asPart, ", ");
3478
			formatStringLiteral(asPart, prosrc, PASS_LFTAB);
3479
		}
3480 3481 3482
	}
	else
	{
3483
		if (strcmp(prosrc, "-") != 0)
3484 3485
		{
			appendPQExpBuffer(asPart, "AS ");
3486
			formatStringLiteral(asPart, prosrc, PASS_LFTAB);
3487
		}
3488 3489
	}

3490
	funcsig = format_function_signature(finfo);
B
Bruce Momjian 已提交
3491

3492 3493 3494 3495
	/* DROP must be fully qualified in case same name appears in pg_catalog */
	appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
					  fmtId(finfo->pronamespace->nspname, force_quotes),
					  funcsig);
B
Bruce Momjian 已提交
3496

3497
	rettypename = getFormattedTypeName(finfo->prorettype, zeroAsOpaque);
3498

3499
	appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcsig);
3500
	appendPQExpBuffer(q, "RETURNS %s%s %s LANGUAGE %s",
3501
					  (proretset[0] == 't') ? "SETOF " : "",
3502
					  rettypename,
3503 3504
					  asPart->data,
					  fmtId(lanname, force_quotes));
3505 3506

	free(rettypename);
3507

3508
	if (provolatile[0] != PROVOLATILE_VOLATILE)
3509
	{
3510
		if (provolatile[0] == PROVOLATILE_IMMUTABLE)
3511
			appendPQExpBuffer(q, " IMMUTABLE");
3512
		else if (provolatile[0] == PROVOLATILE_STABLE)
3513
			appendPQExpBuffer(q, " STABLE");
3514
		else if (provolatile[0] != PROVOLATILE_VOLATILE)
3515 3516
		{
			write_msg(NULL, "Unexpected provolatile value for function %s\n",
3517
					  finfo->proname);
3518 3519
			exit_nicely();
		}
3520
	}	
3521

3522 3523
	if (proimplicit[0] == 't')
		appendPQExpBuffer(q, " IMPLICIT CAST");
3524

3525 3526
	if (proisstrict[0] == 't')
		appendPQExpBuffer(q, " STRICT");
3527

3528 3529 3530
	if (prosecdef[0] == 't')
		appendPQExpBuffer(q, " SECURITY DEFINER");

3531 3532
	appendPQExpBuffer(q, ";\n");

3533
	ArchiveEntry(fout, finfo->oid, funcsig, finfo->pronamespace->nspname,
3534 3535 3536
				 finfo->usename, "FUNCTION", NULL,
				 q->data, delqry->data,
				 NULL, NULL, NULL);
3537

B
Bruce,  
Bruce Momjian 已提交
3538 3539 3540
	/*** Dump Function Comments ***/

	resetPQExpBuffer(q);
3541
	appendPQExpBuffer(q, "FUNCTION %s", funcsig);
3542 3543 3544
	dumpComment(fout, q->data,
				finfo->pronamespace->nspname, finfo->usename,
				finfo->oid, "pg_proc", 0, NULL);
3545 3546

done:
3547 3548 3549
	PQclear(res);

	destroyPQExpBuffer(query);
3550 3551 3552
	destroyPQExpBuffer(q);
	destroyPQExpBuffer(delqry);
	destroyPQExpBuffer(asPart);
3553
	free(funcsig);
3554 3555 3556 3557
}

/*
 * dumpOprs
3558
 *	  writes out to fout the queries to recreate all the user-defined operators
3559
 */
3560
void
3561
dumpOprs(Archive *fout, OprInfo *oprinfo, int numOperators)
3562
{
B
Bruce Momjian 已提交
3563
	int			i;
3564 3565 3566

	for (i = 0; i < numOperators; i++)
	{
3567 3568
		/* Dump only operators in dumpable namespaces */
		if (!oprinfo[i].oprnamespace->dump)
3569 3570 3571
			continue;

		/*
3572
		 * some operators are invalid because they were the result of user
3573 3574
		 * defining operators before commutators exist
		 */
3575
		if (strcmp(oprinfo[i].oprcode, "0") == 0)
3576 3577
			continue;

3578 3579 3580 3581 3582
		/* OK, dump it */
		dumpOneOpr(fout, &oprinfo[i],
				   oprinfo, numOperators);
	}
}
3583

3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631
/*
 * dumpOneOpr
 *	  write out a single operator definition
 */
static void
dumpOneOpr(Archive *fout, OprInfo *oprinfo,
		   OprInfo *g_oprinfo, int numOperators)
{
	PQExpBuffer query = createPQExpBuffer();
	PQExpBuffer q = createPQExpBuffer();
	PQExpBuffer delq = createPQExpBuffer();
	PQExpBuffer oprid = createPQExpBuffer();
	PQExpBuffer details = createPQExpBuffer();
	const char *name;
	PGresult   *res;
	int			ntups;
	int			i_oprkind;
	int			i_oprcode;
	int			i_oprleft;
	int			i_oprright;
	int			i_oprcom;
	int			i_oprnegate;
	int			i_oprrest;
	int			i_oprjoin;
	int			i_oprcanhash;
	int			i_oprlsortop;
	int			i_oprrsortop;
	int			i_oprltcmpop;
	int			i_oprgtcmpop;
	char	   *oprkind;
	char	   *oprcode;
	char	   *oprleft;
	char	   *oprright;
	char	   *oprcom;
	char	   *oprnegate;
	char	   *oprrest;
	char	   *oprjoin;
	char	   *oprcanhash;
	char	   *oprlsortop;
	char	   *oprrsortop;
	char	   *oprltcmpop;
	char	   *oprgtcmpop;

	/* Make sure we are in proper schema so regoperator works correctly */
	selectSourceSchema(oprinfo->oprnamespace->nspname);

	if (g_fout->remoteVersion >= 70300)
	{
3632 3633 3634 3635 3636 3637 3638 3639
		appendPQExpBuffer(query, "SELECT oprkind, "
						  "oprcode::pg_catalog.regprocedure, "
						  "oprleft::pg_catalog.regtype, "
						  "oprright::pg_catalog.regtype, "
						  "oprcom::pg_catalog.regoperator, "
						  "oprnegate::pg_catalog.regoperator, "
						  "oprrest::pg_catalog.regprocedure, "
						  "oprjoin::pg_catalog.regprocedure, "
3640
						  "oprcanhash, "
3641 3642 3643 3644 3645 3646
						  "oprlsortop::pg_catalog.regoperator, "
						  "oprrsortop::pg_catalog.regoperator, "
						  "oprltcmpop::pg_catalog.regoperator, "
						  "oprgtcmpop::pg_catalog.regoperator "
						  "from pg_catalog.pg_operator "
						  "where oid = '%s'::pg_catalog.oid",
3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676
						  oprinfo->oid);
	}
	else if (g_fout->remoteVersion >= 70100)
	{
		appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
						  "CASE WHEN oprleft = 0 THEN '-' "
						  "ELSE format_type(oprleft, NULL) END as oprleft, "
						  "CASE WHEN oprright = 0 THEN '-' "
						  "ELSE format_type(oprright, NULL) END as oprright, "
						  "oprcom, oprnegate, oprrest, oprjoin, "
						  "oprcanhash, oprlsortop, oprrsortop, "
						  "0 as oprltcmpop, 0 as oprgtcmpop "
						  "from pg_operator "
						  "where oid = '%s'::oid",
						  oprinfo->oid);
	}
	else
	{
		appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
						  "CASE WHEN oprleft = 0 THEN '-'::name "
						  "ELSE (select typname from pg_type where oid = oprleft) END as oprleft, "
						  "CASE WHEN oprright = 0 THEN '-'::name "
						  "ELSE (select typname from pg_type where oid = oprright) END as oprright, "
						  "oprcom, oprnegate, oprrest, oprjoin, "
						  "oprcanhash, oprlsortop, oprrsortop, "
						  "0 as oprltcmpop, 0 as oprgtcmpop "
						  "from pg_operator "
						  "where oid = '%s'::oid",
						  oprinfo->oid);
	}
3677

3678 3679 3680 3681 3682 3683 3684
	res = PQexec(g_conn, query->data);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		write_msg(NULL, "query to obtain list of operators failed: %s", PQerrorMessage(g_conn));
		exit_nicely();
	}
3685

3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784
	/* Expecting a single result only */
	ntups = PQntuples(res);
	if (ntups != 1)
	{
		write_msg(NULL, "Got %d rows instead of one from: %s",
				  ntups, query->data);
		exit_nicely();
	}

	i_oprkind = PQfnumber(res, "oprkind");
	i_oprcode = PQfnumber(res, "oprcode");
	i_oprleft = PQfnumber(res, "oprleft");
	i_oprright = PQfnumber(res, "oprright");
	i_oprcom = PQfnumber(res, "oprcom");
	i_oprnegate = PQfnumber(res, "oprnegate");
	i_oprrest = PQfnumber(res, "oprrest");
	i_oprjoin = PQfnumber(res, "oprjoin");
	i_oprcanhash = PQfnumber(res, "oprcanhash");
	i_oprlsortop = PQfnumber(res, "oprlsortop");
	i_oprrsortop = PQfnumber(res, "oprrsortop");
	i_oprltcmpop = PQfnumber(res, "oprltcmpop");
	i_oprgtcmpop = PQfnumber(res, "oprgtcmpop");

	oprkind = PQgetvalue(res, 0, i_oprkind);
	oprcode = PQgetvalue(res, 0, i_oprcode);
	oprleft = PQgetvalue(res, 0, i_oprleft);
	oprright = PQgetvalue(res, 0, i_oprright);
	oprcom = PQgetvalue(res, 0, i_oprcom);
	oprnegate = PQgetvalue(res, 0, i_oprnegate);
	oprrest = PQgetvalue(res, 0, i_oprrest);
	oprjoin = PQgetvalue(res, 0, i_oprjoin);
	oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
	oprlsortop = PQgetvalue(res, 0, i_oprlsortop);
	oprrsortop = PQgetvalue(res, 0, i_oprrsortop);
	oprltcmpop = PQgetvalue(res, 0, i_oprltcmpop);
	oprgtcmpop = PQgetvalue(res, 0, i_oprgtcmpop);

	appendPQExpBuffer(details, "PROCEDURE = %s ",
					  convertRegProcReference(oprcode));

	appendPQExpBuffer(oprid, "%s (",
					  oprinfo->oprname);

	/*
	 * right unary means there's a left arg and left unary means
	 * there's a right arg
	 */
	if (strcmp(oprkind, "r") == 0 ||
		strcmp(oprkind, "b") == 0)
	{
		if (g_fout->remoteVersion >= 70100)
			name = oprleft;
		else
			name = fmtId(oprleft, force_quotes);
		appendPQExpBuffer(details, ",\n\tLEFTARG = %s ", name);
		appendPQExpBuffer(oprid, "%s", name);
	}
	else
		appendPQExpBuffer(oprid, "NONE");

	if (strcmp(oprkind, "l") == 0 ||
		strcmp(oprkind, "b") == 0)
	{
		if (g_fout->remoteVersion >= 70100)
			name = oprright;
		else
			name = fmtId(oprright, force_quotes);
		appendPQExpBuffer(details, ",\n\tRIGHTARG = %s ", name);
		appendPQExpBuffer(oprid, ", %s)", name);
	}
	else
		appendPQExpBuffer(oprid, ", NONE)");

	name = convertOperatorReference(oprcom, g_oprinfo, numOperators);
	if (name)
		appendPQExpBuffer(details, ",\n\tCOMMUTATOR = %s ", name);

	name = convertOperatorReference(oprnegate, g_oprinfo, numOperators);
	if (name)
		appendPQExpBuffer(details, ",\n\tNEGATOR = %s ", name);

	if (strcmp(oprcanhash, "t") == 0)
		appendPQExpBuffer(details, ",\n\tHASHES");

	name = convertRegProcReference(oprrest);
	if (name)
		appendPQExpBuffer(details, ",\n\tRESTRICT = %s ", name);

	name = convertRegProcReference(oprjoin);
	if (name)
		appendPQExpBuffer(details, ",\n\tJOIN = %s ", name);

	name = convertOperatorReference(oprlsortop, g_oprinfo, numOperators);
	if (name)
		appendPQExpBuffer(details, ",\n\tSORT1 = %s ", name);

	name = convertOperatorReference(oprrsortop, g_oprinfo, numOperators);
	if (name)
		appendPQExpBuffer(details, ",\n\tSORT2 = %s ", name);
3785

3786 3787 3788
	name = convertOperatorReference(oprltcmpop, g_oprinfo, numOperators);
	if (name)
		appendPQExpBuffer(details, ",\n\tLTCMP = %s ", name);
3789

3790 3791 3792
	name = convertOperatorReference(oprgtcmpop, g_oprinfo, numOperators);
	if (name)
		appendPQExpBuffer(details, ",\n\tGTCMP = %s ", name);
3793

3794 3795 3796
	/* DROP must be fully qualified in case same name appears in pg_catalog */
	appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
					  fmtId(oprinfo->oprnamespace->nspname, force_quotes),
3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807
					  oprid->data);

	appendPQExpBuffer(q, "CREATE OPERATOR %s (%s);\n",
					  oprinfo->oprname, details->data);

	ArchiveEntry(fout, oprinfo->oid, oprinfo->oprname,
				 oprinfo->oprnamespace->nspname, oprinfo->usename,
				 "OPERATOR", NULL,
				 q->data, delq->data,
				 NULL, NULL, NULL);

3808 3809 3810 3811 3812 3813 3814
	/*** Dump Operator Comments ***/

	resetPQExpBuffer(q);
	appendPQExpBuffer(q, "OPERATOR %s", oprid->data);
	dumpComment(fout, q->data,
				oprinfo->oprnamespace->nspname, oprinfo->usename,
				oprinfo->oid, "pg_operator", 0, NULL);
3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849

	PQclear(res);

	destroyPQExpBuffer(query);
	destroyPQExpBuffer(q);
	destroyPQExpBuffer(delq);
	destroyPQExpBuffer(oprid);
	destroyPQExpBuffer(details);
}

/*
 * Convert a function reference obtained from pg_operator
 *
 * Returns what to print, or NULL if function references is InvalidOid
 *
 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
 * argument-types part.  In prior versions, the input is a REGPROC display.
 */
static const char *
convertRegProcReference(const char *proc)
{
	/* In all cases "-" means a null reference */
	if (strcmp(proc, "-") == 0)
		return NULL;

	if (g_fout->remoteVersion >= 70300)
	{
		char   *name;
		char   *paren;
		bool	inquote;

		name = strdup(proc);
		/* find non-double-quoted left paren */
		inquote = false;
		for (paren = name; *paren; paren++)
3850
		{
3851
			if (*paren == '(' && !inquote)
3852
			{
3853 3854
				*paren = '\0';
				break;
3855
			}
3856 3857
			if (*paren == '"')
				inquote = !inquote;
3858
		}
3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888
		return name;
	}

	/* REGPROC before 7.3 does not quote its result */
	return fmtId(proc, false);
}

/*
 * Convert an operator cross-reference obtained from pg_operator
 *
 * Returns what to print, or NULL to print nothing
 *
 * In 7.3 the input is a REGOPERATOR display; we have to strip the
 * argument-types part.  In prior versions, the input is just a
 * numeric OID, which we search our operator list for.
 */
static const char *
convertOperatorReference(const char *opr,
						 OprInfo *g_oprinfo, int numOperators)
{
	char   *name;

	/* In all cases "0" means a null reference */
	if (strcmp(opr, "0") == 0)
		return NULL;

	if (g_fout->remoteVersion >= 70300)
	{
		char   *paren;
		bool	inquote;
3889

3890 3891 3892 3893
		name = strdup(opr);
		/* find non-double-quoted left paren */
		inquote = false;
		for (paren = name; *paren; paren++)
3894
		{
3895
			if (*paren == '(' && !inquote)
3896
			{
3897 3898
				*paren = '\0';
				break;
3899
			}
3900 3901
			if (*paren == '"')
				inquote = !inquote;
3902
		}
3903
		return name;
3904
	}
3905

3906 3907 3908 3909 3910
	name = findOprByOid(g_oprinfo, numOperators, opr);
	if (name == NULL)
		write_msg(NULL, "WARNING: cannot find operator with OID %s\n",
				  opr);
	return name;
3911 3912 3913 3914
}

/*
 * dumpAggs
3915
 *	  writes out to fout the queries to create all the user-defined aggregates
3916 3917
 */
void
3918
dumpAggs(Archive *fout, AggInfo agginfo[], int numAggs)
3919
{
B
Bruce Momjian 已提交
3920
	int			i;
3921 3922 3923 3924 3925 3926 3927 3928

	for (i = 0; i < numAggs; i++)
	{
		/* Dump only aggs in dumpable namespaces */
		if (!agginfo[i].aggnamespace->dump)
			continue;

		dumpOneAgg(fout, &agginfo[i]);
3929 3930 3931 3932 3933 3934
		if (!aclsSkip)
			dumpAggACL(fout, &agginfo[i]);
	}
}


3935 3936 3937 3938 3939 3940
/*
 * format_aggregate_signature: generate aggregate name and argument list
 *
 * The argument type names are qualified if needed.  The aggregate name
 * is never qualified.
 */
3941 3942 3943 3944 3945 3946 3947 3948 3949 3950
static char *
format_aggregate_signature(AggInfo *agginfo, Archive *fout)
{
	PQExpBufferData buf;
	bool anybasetype;

	initPQExpBuffer(&buf);
	appendPQExpBuffer(&buf, "%s",
					  fmtId(agginfo->aggname, force_quotes));

3951
	anybasetype = (strcmp(agginfo->aggbasetype, "0") == 0);
3952

3953
	/* If using regtype or format_type, fmtbasetype is already quoted */
3954 3955 3956 3957 3958
	if (fout->remoteVersion >= 70100)
	{
		if (anybasetype)
			appendPQExpBuffer(&buf, "(*)");
		else
3959
			appendPQExpBuffer(&buf, "(%s)", agginfo->fmtbasetype);
3960
	}
3961 3962 3963 3964 3965 3966
	else
	{
		if (anybasetype)
			appendPQExpBuffer(&buf, "(*)");
		else
			appendPQExpBuffer(&buf, "(%s)",
3967
							  fmtId(agginfo->fmtbasetype, force_quotes));
3968 3969 3970
	}

	return buf.data;
3971 3972
}

3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985

static void
dumpAggACL(Archive *fout, AggInfo *finfo)
{
	char *aggsig;

	aggsig = format_aggregate_signature(finfo, fout);
	dumpACL(fout, "FUNCTION", aggsig, finfo->aggnamespace->nspname,
			finfo->usename, finfo->aggacl, finfo->oid);
	free(aggsig);
}


3986 3987 3988 3989 3990 3991 3992 3993
/*
 * dumpOneAgg
 *	  write out a single aggregate definition
 */
static void
dumpOneAgg(Archive *fout, AggInfo *agginfo)
{
	PQExpBuffer query = createPQExpBuffer();
3994
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3995
	PQExpBuffer delq = createPQExpBuffer();
3996
	PQExpBuffer details = createPQExpBuffer();
3997
	char	   *aggSig;
3998 3999 4000 4001 4002 4003
	PGresult   *res;
	int			ntups;
	int			i_aggtransfn;
	int			i_aggfinalfn;
	int			i_aggtranstype;
	int			i_agginitval;
4004
	int			i_fmtbasetype;
4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019
	int			i_convertok;
	const char *aggtransfn;
	const char *aggfinalfn;
	const char *aggtranstype;
	const char *agginitval;
	bool		convertok;
	bool		anybasetype;

	/* Make sure we are in proper schema */
	selectSourceSchema(agginfo->aggnamespace->nspname);

	/* Get aggregate-specific details */
	if (g_fout->remoteVersion >= 70300)
	{
		appendPQExpBuffer(query, "SELECT aggtransfn, "
4020
						  "aggfinalfn, aggtranstype::pg_catalog.regtype, "
4021
						  "agginitval, "
4022
						  "proargtypes[0]::pg_catalog.regtype as fmtbasetype, "
4023
						  "'t'::boolean as convertok "
4024
						  "from pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
4025
						  "where a.aggfnoid = p.oid "
4026
						  "and p.oid = '%s'::pg_catalog.oid",
4027 4028 4029 4030 4031 4032
						  agginfo->oid);
	}
	else if (g_fout->remoteVersion >= 70100)
	{
		appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
						  "format_type(aggtranstype, NULL) as aggtranstype, "
4033 4034 4035 4036
						  "agginitval, "
						  "CASE WHEN aggbasetype = 0 THEN '-' "
						  "ELSE format_type(aggbasetype, NULL) END as fmtbasetype, "
						  "'t'::boolean as convertok "
4037 4038 4039 4040 4041 4042 4043 4044 4045 4046
						  "from pg_aggregate "
						  "where oid = '%s'::oid",
						  agginfo->oid);
	}
	else
	{
		appendPQExpBuffer(query, "SELECT aggtransfn1 as aggtransfn, "
						  "aggfinalfn, "
						  "(select typname from pg_type where oid = aggtranstype1) as aggtranstype, "
						  "agginitval1 as agginitval, "
4047
						  "(select typname from pg_type where oid = aggbasetype) as fmtbasetype, "
4048 4049 4050 4051 4052
						  "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) as convertok "
						  "from pg_aggregate "
						  "where oid = '%s'::oid",
						  agginfo->oid);
	}
4053

4054 4055 4056
	res = PQexec(g_conn, query->data);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
4057
	{
4058 4059 4060 4061
		write_msg(NULL, "query to obtain list of aggregate functions failed: %s",
				  PQerrorMessage(g_conn));
		exit_nicely();
	}
4062

4063 4064 4065 4066 4067 4068 4069 4070
	/* Expecting a single result only */
	ntups = PQntuples(res);
	if (ntups != 1)
	{
		write_msg(NULL, "Got %d rows instead of one from: %s",
				  ntups, query->data);
		exit_nicely();
	}
B
Hi, all  
Bruce Momjian 已提交
4071

4072 4073 4074 4075
	i_aggtransfn = PQfnumber(res, "aggtransfn");
	i_aggfinalfn = PQfnumber(res, "aggfinalfn");
	i_aggtranstype = PQfnumber(res, "aggtranstype");
	i_agginitval = PQfnumber(res, "agginitval");
4076
	i_fmtbasetype = PQfnumber(res, "fmtbasetype");
4077
	i_convertok = PQfnumber(res, "convertok");
4078

4079 4080 4081 4082
	aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
	aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
	aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
	agginitval = PQgetvalue(res, 0, i_agginitval);
4083 4084
	/* we save fmtbasetype so that dumpAggACL can use it later */
	agginfo->fmtbasetype = strdup(PQgetvalue(res, 0, i_fmtbasetype));
4085
	convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
4086

4087
	aggSig = format_aggregate_signature(agginfo, g_fout);
4088

4089 4090 4091
	if (!convertok)
	{
		write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
4092
				  aggSig);
4093 4094

		appendPQExpBuffer(q, "-- WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
4095 4096
						  aggSig);
		ArchiveEntry(fout, agginfo->oid, aggSig,
4097 4098 4099 4100 4101 4102
					 agginfo->aggnamespace->nspname, agginfo->usename,
					 "WARNING", NULL,
					 q->data, "" /* Del */ ,
					 NULL, NULL, NULL);
		return;
	}
4103

4104
	anybasetype = (strcmp(agginfo->aggbasetype, "0") == 0);
4105

4106 4107 4108 4109
	if (g_fout->remoteVersion >= 70300)
	{
		/* If using 7.3's regproc or regtype, data is already quoted */
		appendPQExpBuffer(details, "BASETYPE = %s, SFUNC = %s, STYPE = %s",
4110
						  anybasetype ? "'any'" : agginfo->fmtbasetype,
4111 4112 4113 4114 4115 4116 4117
						  aggtransfn,
						  aggtranstype);
	}
	else if (g_fout->remoteVersion >= 70100)
	{
		/* format_type quotes, regproc does not */
		appendPQExpBuffer(details, "BASETYPE = %s, SFUNC = %s, STYPE = %s",
4118
						  anybasetype ? "'any'" : agginfo->fmtbasetype,
4119 4120 4121 4122 4123 4124 4125 4126
						  fmtId(aggtransfn, force_quotes),
						  aggtranstype);
	}
	else
	{
		/* need quotes all around */
		appendPQExpBuffer(details, "BASETYPE = %s, ",
						  anybasetype ? "'any'" :
4127
						  fmtId(agginfo->fmtbasetype, force_quotes));
4128 4129 4130 4131 4132
		appendPQExpBuffer(details, "SFUNC = %s, ",
						  fmtId(aggtransfn, force_quotes));
		appendPQExpBuffer(details, "STYPE = %s",
						  fmtId(aggtranstype, force_quotes));
	}
4133

4134 4135 4136 4137 4138
	if (!PQgetisnull(res, 0, i_agginitval))
	{
		appendPQExpBuffer(details, ", INITCOND = ");
		formatStringLiteral(details, agginitval, CONV_ALL);
	}
4139

4140 4141 4142 4143 4144
	if (strcmp(aggfinalfn, "-") != 0)
	{
		appendPQExpBuffer(details, ", FINALFUNC = %s",
						  aggfinalfn);
	}
4145

4146 4147 4148 4149
	/* DROP must be fully qualified in case same name appears in pg_catalog */
	appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
					  fmtId(agginfo->aggnamespace->nspname, force_quotes),
					  aggSig);
4150

4151 4152 4153
	appendPQExpBuffer(q, "CREATE AGGREGATE %s ( %s );\n",
					  fmtId(agginfo->aggname, force_quotes),
					  details->data);
4154

4155
	ArchiveEntry(fout, agginfo->oid, aggSig,
4156 4157 4158 4159
				 agginfo->aggnamespace->nspname, agginfo->usename,
				 "AGGREGATE", NULL,
				 q->data, delq->data,
				 NULL, NULL, NULL);
4160

4161
	/*** Dump Aggregate Comments ***/
B
Bruce,  
Bruce Momjian 已提交
4162

4163
	resetPQExpBuffer(q);
4164
	appendPQExpBuffer(q, "AGGREGATE %s", aggSig);
4165 4166 4167 4168 4169 4170 4171 4172
	if (g_fout->remoteVersion >= 70300)
		dumpComment(fout, q->data,
					agginfo->aggnamespace->nspname, agginfo->usename,
					agginfo->oid, "pg_proc", 0, NULL);
	else
		dumpComment(fout, q->data,
					agginfo->aggnamespace->nspname, agginfo->usename,
					agginfo->oid, "pg_aggregate", 0, NULL);
B
Bruce,  
Bruce Momjian 已提交
4173

4174
	PQclear(res);
4175

4176
	destroyPQExpBuffer(query);
4177 4178 4179
	destroyPQExpBuffer(q);
	destroyPQExpBuffer(delq);
	destroyPQExpBuffer(details);
4180
	free(aggSig);
4181 4182
}

4183

4184 4185 4186 4187 4188
/*
 * These are some support functions to fix the acl problem of pg_dump
 *
 * Matthew C. Aycock 12/02/97
 */
4189 4190 4191

/* Append a keyword to a keyword list, inserting comma if needed.
 * Caller must make aclbuf big enough for all possible keywords.
4192
 */
4193
static void
B
Bruce Momjian 已提交
4194
AddAcl(char *aclbuf, const char *keyword)
4195
{
4196 4197 4198
	if (*aclbuf)
		strcat(aclbuf, ",");
	strcat(aclbuf, keyword);
4199
}
4200

4201
/*
4202 4203 4204 4205 4206
 * This will take a string of privilege code letters and return a malloced,
 * comma delimited string of keywords for GRANT.
 *
 * Note: for cross-version compatibility, it's important to use ALL when
 * appropriate.
4207
 */
V
Vadim B. Mikheev 已提交
4208
static char *
4209
GetPrivileges(Archive *AH, const char *s, const char *type)
4210
{
4211
	char		aclbuf[100];
4212
	bool		all = true;
4213

4214
	aclbuf[0] = '\0';
4215

4216 4217 4218 4219 4220
#define CONVERT_PRIV(code,keywd) \
	if (strchr(s, code)) \
		AddAcl(aclbuf, keywd); \
	else \
		all = false
4221

4222 4223 4224 4225 4226
	if (strcmp(type, "TABLE")==0)
	{
		CONVERT_PRIV('a', "INSERT");
		CONVERT_PRIV('r', "SELECT");
		CONVERT_PRIV('R', "RULE");
4227

4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241
		if (AH->remoteVersion >= 70200)
		{
			CONVERT_PRIV('w', "UPDATE");
			CONVERT_PRIV('d', "DELETE");
			CONVERT_PRIV('x', "REFERENCES");
			CONVERT_PRIV('t', "TRIGGER");
		}
		else
		{
			/* 7.0 and 7.1 have a simpler worldview */
			CONVERT_PRIV('w', "UPDATE,DELETE");
		}
	}
	else if (strcmp(type, "FUNCTION")==0)
4242
	{
4243
		CONVERT_PRIV('X', "EXECUTE");
4244
	}
4245
	else if (strcmp(type, "LANGUAGE")==0)
4246
	{
4247
		CONVERT_PRIV('U', "USAGE");
4248
	}
4249 4250 4251 4252 4253
	else if (strcmp(type, "SCHEMA")==0)
	{
		CONVERT_PRIV('C', "CREATE");
		CONVERT_PRIV('U', "USAGE");
	}
4254 4255
	else
		abort();
4256

4257 4258 4259 4260 4261 4262
#undef CONVERT_PRIV

	if (all)
		return strdup("ALL");
	else
		return strdup(aclbuf);
4263
}
4264

B
Bruce Momjian 已提交
4265

B
Bruce Momjian 已提交
4266
/*
4267 4268
 * Write out grant/revoke information
 *
4269
 * 'type' must be TABLE, FUNCTION, LANGUAGE, or SCHEMA.  'name' is the
4270
 * formatted name of the object.  Must be quoted etc. already.
4271 4272 4273 4274 4275
 * 'nspname' is the namespace the object is in (NULL if none).
 * 'usename' is the owner, NULL if there is no owner (for languages).
 * 'acls' is the string read out of the fooacl system catalog field;
 * it will be parsed here.
 * 'objoid' is the OID of the object for purposes of ordering.
B
Bruce Momjian 已提交
4276
 */
4277
static void
4278 4279 4280
dumpACL(Archive *fout, const char *type, const char *name,
		const char *nspname, const char *usename,
		const char *acls, const char *objoid)
B
Bruce Momjian 已提交
4281
{
B
Bruce Momjian 已提交
4282
	char	   *aclbuf,
B
Bruce Momjian 已提交
4283 4284 4285
			   *tok,
			   *eqpos,
			   *priv;
4286 4287
	PQExpBuffer sql;
	bool		found_owner_privs = false;
4288 4289

	if (strlen(acls) == 0)
4290
		return;					/* object has default permissions */
4291

4292
	sql = createPQExpBuffer();
4293 4294 4295

	/* Make a working copy of acls so we can use strtok */
	aclbuf = strdup(acls);
B
Bruce Momjian 已提交
4296

4297 4298
	/* Scan comma-separated ACL items */
	for (tok = strtok(aclbuf, ","); tok != NULL; tok = strtok(NULL, ","))
4299
	{
B
Bruce Momjian 已提交
4300 4301 4302
		/*
		 * Token may start with '{' and/or '"'.  Actually only the start
		 * of the string should have '{', but we don't verify that.
4303 4304 4305 4306 4307 4308 4309 4310
		 */
		if (*tok == '{')
			tok++;
		if (*tok == '"')
			tok++;

		/* User name is string up to = in tok */
		eqpos = strchr(tok, '=');
B
Bruce Momjian 已提交
4311
		if (!eqpos)
B
Bruce Momjian 已提交
4312
		{
4313 4314
			write_msg(NULL, "could not parse ACL list ('%s') for %s %s\n",
					  acls, type, name);
4315
			exit_nicely();
B
Bruce Momjian 已提交
4316
		}
4317
		*eqpos = '\0';			/* it's ok to clobber aclbuf */
B
Bruce Momjian 已提交
4318

B
Bruce Momjian 已提交
4319
		/*
4320
		 * Parse the privileges (right-hand side).
B
Bruce Momjian 已提交
4321
		 */
4322 4323
		priv = GetPrivileges(fout, eqpos + 1, type);

4324
		if (*priv)
4325
		{
4326
			if (usename && strcmp(tok, usename) == 0)
4327
			{
4328 4329 4330 4331 4332 4333 4334
				/*
				 * For the owner, the default privilege level is ALL.
				 */
				found_owner_privs = true;
				if (strcmp(priv, "ALL") != 0)
				{
					/* NB: only one fmtId per appendPQExpBuffer! */
4335 4336
					appendPQExpBuffer(sql, "REVOKE ALL ON %s %s FROM ",
									  type, name);
4337
					appendPQExpBuffer(sql, "%s;\n", fmtId(tok, force_quotes));
4338 4339
					appendPQExpBuffer(sql, "GRANT %s ON %s %s TO ",
									  priv, type, name);
4340 4341
					appendPQExpBuffer(sql, "%s;\n", fmtId(tok, force_quotes));
				}
4342
			}
4343
			else
4344
			{
4345 4346 4347
				/*
				 * Otherwise can assume we are starting from no privs.
				 */
4348 4349
				appendPQExpBuffer(sql, "GRANT %s ON %s %s TO ",
								  priv, type, name);
4350 4351 4352 4353 4354 4355 4356 4357 4358
				if (eqpos == tok)
				{
					/* Empty left-hand side means "PUBLIC" */
					appendPQExpBuffer(sql, "PUBLIC;\n");
				}
				else if (strncmp(tok, "group ", strlen("group ")) == 0)
					appendPQExpBuffer(sql, "GROUP %s;\n",
									  fmtId(tok + strlen("group "),
											force_quotes));
4359
				else
4360
					appendPQExpBuffer(sql, "%s;\n", fmtId(tok, force_quotes));
4361
			}
4362
		}
4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379
		else
		{
			/* No privileges.  Issue explicit REVOKE for safety. */
			appendPQExpBuffer(sql, "REVOKE ALL ON %s %s FROM ",
							  type, name);
			if (eqpos == tok)
			{
				/* Empty left-hand side means "PUBLIC" */
				appendPQExpBuffer(sql, "PUBLIC;\n");
			}
			else if (strncmp(tok, "group ", strlen("group ")) == 0)
				appendPQExpBuffer(sql, "GROUP %s;\n",
								  fmtId(tok + strlen("group "),
										force_quotes));
			else
				appendPQExpBuffer(sql, "%s;\n", fmtId(tok, force_quotes));
		}
4380
		free(priv);
B
Bruce Momjian 已提交
4381
	}
4382

4383 4384 4385
	/*
	 * If we didn't find any owner privs, the owner must have revoked 'em all
	 */
4386
	if (!found_owner_privs && usename)
4387
	{
4388 4389 4390
		appendPQExpBuffer(sql, "REVOKE ALL ON %s %s FROM ",
						  type, name);
		appendPQExpBuffer(sql, "%s;\n", fmtId(usename, force_quotes));
4391 4392
	}

4393 4394
	ArchiveEntry(fout, objoid, name, nspname, usename ? usename : "",
				 "ACL", NULL, sql->data, "", NULL, NULL, NULL);
4395

4396
	free(aclbuf);
4397
	destroyPQExpBuffer(sql);
B
Bruce Momjian 已提交
4398 4399
}

4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411

static void
dumpTableACL(Archive *fout, TableInfo *tbinfo)
{
	char * tmp = strdup( fmtId(tbinfo->relname, force_quotes) );
	dumpACL(fout, "TABLE", tmp, tbinfo->relnamespace->nspname,
			tbinfo->usename, tbinfo->relacl,
			tbinfo->viewoid != NULL ? tbinfo->viewoid : tbinfo->oid);
	free(tmp);
}


4412 4413 4414 4415 4416
/*
 * dumpTables:
 *	  write out to fout the declarations (not data) of all user-defined tables
 */
void
4417
dumpTables(Archive *fout, TableInfo tblinfo[], int numTables,
4418
		   const bool aclsSkip, const bool schemaOnly, const bool dataOnly)
4419
{
4420
	int			i;
4421

4422 4423
	/* Dump sequences first, in case they are referenced in table defn's */
	for (i = 0; i < numTables; i++)
4424
	{
4425
		TableInfo	   *tbinfo = &tblinfo[i];
4426

4427 4428 4429
		if (tbinfo->relkind != RELKIND_SEQUENCE)
			continue;
		if (tbinfo->dump)
4430
		{
4431 4432
			dumpOneSequence(fout, tbinfo, schemaOnly, dataOnly);
			if (!dataOnly && !aclsSkip)
4433
				dumpTableACL(fout, tbinfo);
4434 4435
		}
	}
4436 4437

	if (!dataOnly)
4438
	{
4439
		for (i = 0; i < numTables; i++)
4440
		{
4441
			TableInfo	   *tbinfo = &tblinfo[i];
4442

4443 4444 4445 4446 4447 4448 4449
			if (tbinfo->relkind == RELKIND_SEQUENCE) /* already dumped */
				continue;

			if (tbinfo->dump)
			{
				dumpOneTable(fout, tbinfo, tblinfo);
				if (!aclsSkip)
4450
					dumpTableACL(fout, tbinfo);
4451 4452
			}
		}
4453 4454
	}
}
4455

4456
/*
4457 4458
 * dumpOneTable
 *	  write the declaration (not data) of one user-defined table or view
4459
 */
4460 4461
static void
dumpOneTable(Archive *fout, TableInfo *tbinfo, TableInfo *g_tblinfo)
4462
{
4463
	PQExpBuffer query = createPQExpBuffer();
4464
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
4465
	PQExpBuffer delq = createPQExpBuffer();
4466
	PGresult   *res;
4467
	int			numParents;
4468
	int		   *parentIndexes;
B
Bruce Momjian 已提交
4469
	int			actual_atts;	/* number of attrs in this CREATE statment */
4470
	char	   *reltypename;
4471
	char	   *objoid;
4472
	const char *((*commentDeps)[]);
4473 4474
	int			j,
				k;
4475

4476 4477
	/* Make sure we are in proper schema */
	selectSourceSchema(tbinfo->relnamespace->nspname);
4478

4479 4480
	/* Is it a table or a view? */
	if (tbinfo->relkind == RELKIND_VIEW)
4481
	{
4482
		char	   *viewdef;
4483

4484
		reltypename = "VIEW";
4485

4486 4487 4488 4489
		/* Fetch the view definition */
		if (g_fout->remoteVersion >= 70300)
		{
			/* Beginning in 7.3, viewname is not unique; use OID */
4490
			appendPQExpBuffer(query, "SELECT pg_catalog.pg_get_viewdef(ev_class) as viewdef, "
4491
							  "oid as view_oid"
4492 4493
							  " from pg_catalog.pg_rewrite where"
							  " ev_class = '%s'::pg_catalog.oid and"
4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505
							  " rulename = '_RETURN';",
							  tbinfo->oid);
		}
		else
		{
			appendPQExpBuffer(query, "SELECT definition as viewdef, "
							  "(select oid from pg_rewrite where "
							  " rulename=('_RET' || viewname)::name) as view_oid"
							  " from pg_views where viewname = ");
			formatStringLiteral(query, tbinfo->relname, CONV_ALL);
			appendPQExpBuffer(query, ";");
		}
4506

4507 4508 4509 4510 4511 4512 4513
		res = PQexec(g_conn, query->data);
		if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
		{
			write_msg(NULL, "query to obtain definition of view \"%s\" failed: %s",
					  tbinfo->relname, PQerrorMessage(g_conn));
			exit_nicely();
		}
4514

4515 4516 4517 4518 4519
		if (PQntuples(res) != 1)
		{
			if (PQntuples(res) < 1)
				write_msg(NULL, "query to obtain definition of view \"%s\" returned no data\n",
						  tbinfo->relname);
4520
			else
4521 4522 4523 4524
				write_msg(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
						  tbinfo->relname);
			exit_nicely();
		}
B
Bruce Momjian 已提交
4525

4526 4527 4528 4529 4530 4531
		if (PQgetisnull(res, 0, 1))
		{
			write_msg(NULL, "query to obtain definition of view \"%s\" returned NULL oid\n",
					  tbinfo->relname);
			exit_nicely();
		}
4532

4533
		viewdef = PQgetvalue(res, 0, 0);
4534

4535 4536 4537 4538 4539 4540
		if (strlen(viewdef) == 0)
		{
			write_msg(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
					  tbinfo->relname);
			exit_nicely();
		}
4541

4542 4543 4544 4545
		/* We use the OID of the view rule as the object OID */
		objoid = strdup(PQgetvalue(res, 0, 1));
		/* Save it for use by dumpACL, too */
		tbinfo->viewoid = objoid;
4546

4547 4548 4549 4550
		/* DROP must be fully qualified in case same name appears in pg_catalog */
		appendPQExpBuffer(delq, "DROP VIEW %s.",
						  fmtId(tbinfo->relnamespace->nspname, force_quotes));
		appendPQExpBuffer(delq, "%s;\n",
4551
						  fmtId(tbinfo->relname, force_quotes));
4552

4553 4554
		appendPQExpBuffer(q, "CREATE VIEW %s AS %s\n",
						  fmtId(tbinfo->relname, force_quotes), viewdef);
4555

4556
		PQclear(res);
B
Hi all  
Bruce Momjian 已提交
4557

4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573
		/*
		 * Views can have default values -- however, they must be
		 * specified in an ALTER TABLE command after the view has
		 * been created, not in the view definition itself.
		 */
		for (j = 0; j < tbinfo->numatts; j++)
		{
			if (tbinfo->adef_expr[j] != NULL && !tbinfo->inhAttrDef[j])
			{
				appendPQExpBuffer(q, "ALTER TABLE %s ",
								  fmtId(tbinfo->relname, force_quotes));
				appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
								  fmtId(tbinfo->attnames[j], force_quotes),
								  tbinfo->adef_expr[j]);
			}
		}
4574

4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585
		commentDeps = malloc(sizeof(char *) * 2);
		(*commentDeps)[0] = strdup(objoid);
		(*commentDeps)[1] = NULL;		/* end of list */
	}
	else
	{
		reltypename = "TABLE";
		objoid = tbinfo->oid;
		commentDeps = NULL;
		numParents = tbinfo->numParents;
		parentIndexes = tbinfo->parentIndexes;
4586

4587 4588 4589 4590
		/* DROP must be fully qualified in case same name appears in pg_catalog */
		appendPQExpBuffer(delq, "DROP TABLE %s.",
						  fmtId(tbinfo->relnamespace->nspname, force_quotes));
		appendPQExpBuffer(delq, "%s;\n",
4591
						  fmtId(tbinfo->relname, force_quotes));
4592

4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603
		appendPQExpBuffer(q, "CREATE TABLE %s (\n\t",
						  fmtId(tbinfo->relname, force_quotes));
		actual_atts = 0;
		for (j = 0; j < tbinfo->numatts; j++)
		{
			/* Is this one of the table's own attrs ? */
			if (!tbinfo->inhAttrs[j])
			{
				/* Format properly if not first attr */
				if (actual_atts > 0)
					appendPQExpBuffer(q, ",\n\t");
4604

4605 4606 4607
				/* Attr name & type */
				appendPQExpBuffer(q, "%s ",
								  fmtId(tbinfo->attnames[j], force_quotes));
4608

4609 4610 4611 4612 4613 4614 4615
				/* If no format_type, fake it */
				if (g_fout->remoteVersion >= 70100)
					appendPQExpBuffer(q, "%s", tbinfo->atttypnames[j]);
				else
					appendPQExpBuffer(q, "%s",
									  myFormatType(tbinfo->atttypnames[j],
												   tbinfo->atttypmod[j]));
4616

4617 4618 4619 4620
				/* Default value */
				if (tbinfo->adef_expr[j] != NULL && !tbinfo->inhAttrDef[j])
					appendPQExpBuffer(q, " DEFAULT %s",
									  tbinfo->adef_expr[j]);
B
Hi all  
Bruce Momjian 已提交
4621

4622 4623 4624
				/* Not Null constraint */
				if (tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
					appendPQExpBuffer(q, " NOT NULL");
4625

4626
				actual_atts++;
4627
			}
4628
		}
B
Bruce Momjian 已提交
4629

4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641
		/*
		 * Add non-inherited CHECK constraints, if any. If a
		 * constraint matches by name and condition with a constraint
		 * belonging to a parent class (OR conditions match and both names
		 * start with '$'), we assume it was inherited.
		 */
		if (tbinfo->ncheck > 0)
		{
			PGresult   *res2;
			int			i_rcname,
						i_rcsrc;
			int			ntups2;
B
Bruce Momjian 已提交
4642

4643 4644 4645
			if (g_verbose)
				write_msg(NULL, "finding CHECK constraints for table %s\n",
						  tbinfo->relname);
4646

4647
			resetPQExpBuffer(query);
4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680
			if (g_fout->remoteVersion >= 70300)
				appendPQExpBuffer(query, "SELECT rcname, rcsrc"
								  " from pg_catalog.pg_relcheck c1"
								  " where rcrelid = '%s'::pg_catalog.oid "
								  "   and not exists "
								  "  (select 1 from "
								  "    pg_catalog.pg_relcheck c2, "
								  "    pg_catalog.pg_inherits i "
								  "    where i.inhrelid = c1.rcrelid "
								  "      and (c2.rcname = c1.rcname "
								  "          or (c2.rcname[0] = '$' "
								  "              and c1.rcname[0] = '$')"
								  "          )"
								  "      and c2.rcsrc = c1.rcsrc "
								  "      and c2.rcrelid = i.inhparent) "
								  " order by rcname ",
								  tbinfo->oid);
			else
				appendPQExpBuffer(query, "SELECT rcname, rcsrc"
								  " from pg_relcheck c1"
								  " where rcrelid = '%s'::oid "
								  "   and not exists "
								  "  (select 1 from pg_relcheck c2, "
								  "    pg_inherits i "
								  "    where i.inhrelid = c1.rcrelid "
								  "      and (c2.rcname = c1.rcname "
								  "          or (c2.rcname[0] = '$' "
								  "              and c1.rcname[0] = '$')"
								  "          )"
								  "      and c2.rcsrc = c1.rcsrc "
								  "      and c2.rcrelid = i.inhparent) "
								  " order by rcname ",
								  tbinfo->oid);
4681 4682 4683 4684 4685 4686
			res2 = PQexec(g_conn, query->data);
			if (!res2 ||
				PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
				write_msg(NULL, "query to obtain check constraints failed: %s", PQerrorMessage(g_conn));
				exit_nicely();
4687
			}
4688 4689
			ntups2 = PQntuples(res2);
			if (ntups2 > tbinfo->ncheck)
4690
			{
4691 4692 4693 4694
				write_msg(NULL, "expected %d check constraints on table \"%s\" but found %d\n",
						  tbinfo->ncheck, tbinfo->relname, ntups2);
				write_msg(NULL, "(The system catalogs might be corrupted.)\n");
				exit_nicely();
B
Bruce,  
Bruce Momjian 已提交
4695
			}
4696

4697 4698
			i_rcname = PQfnumber(res2, "rcname");
			i_rcsrc = PQfnumber(res2, "rcsrc");
4699

4700 4701 4702 4703 4704 4705 4706
			for (j = 0; j < ntups2; j++)
			{
				const char *name = PQgetvalue(res2, j, i_rcname);
				const char *expr = PQgetvalue(res2, j, i_rcsrc);

				if (actual_atts + j > 0)
					appendPQExpBuffer(q, ",\n\t");
4707

4708 4709 4710 4711 4712 4713
				if (name[0] != '$')
					appendPQExpBuffer(q, "CONSTRAINT %s ",
									  fmtId(name, force_quotes));
				appendPQExpBuffer(q, "CHECK (%s)", expr);
			}
			PQclear(res2);
4714
		}
4715

4716 4717 4718 4719 4720 4721 4722 4723 4724
		/*
		 * Primary Key: In versions of PostgreSQL prior to 7.2, we
		 * needed to include the primary key in the table definition.
		 * However, this is not ideal because it creates an index
		 * on the table, which makes COPY slower. As of release 7.2,
		 * we can add primary keys to a table after it has been created,
		 * using ALTER TABLE; see dumpIndexes() for more information.
		 * Therefore, we ignore primary keys in this function.
		 */
4725

4726
		appendPQExpBuffer(q, "\n)");
4727

4728 4729 4730 4731 4732 4733
		if (numParents > 0)
		{
			appendPQExpBuffer(q, "\nINHERITS (");
			for (k = 0; k < numParents; k++)
			{
				TableInfo  *parentRel = &g_tblinfo[parentIndexes[k]];
4734

4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745
				if (k > 0)
					appendPQExpBuffer(q, ", ");
				if (parentRel->relnamespace != tbinfo->relnamespace)
					appendPQExpBuffer(q, "%s.",
									  fmtId(parentRel->relnamespace->nspname,
											force_quotes));
				appendPQExpBuffer(q, "%s",
								  fmtId(parentRel->relname, force_quotes));
			}
			appendPQExpBuffer(q, ")");
		}
4746

4747 4748
		if (!tbinfo->hasoids)
			appendPQExpBuffer(q, " WITHOUT OIDS");
4749

4750
		appendPQExpBuffer(q, ";\n");
4751 4752
	}

4753 4754 4755 4756
	ArchiveEntry(fout, objoid, tbinfo->relname,
				 tbinfo->relnamespace->nspname, tbinfo->usename,
				 reltypename, NULL, q->data, delq->data,
				 NULL, NULL, NULL);
4757

4758 4759 4760
	/* Dump Table Comments */
	dumpTableComment(fout, tbinfo, reltypename, commentDeps);

4761 4762 4763 4764 4765 4766 4767 4768 4769
	if (commentDeps)
	{
		for (j = 0; (*commentDeps)[j] != NULL; j++)
		{
			free((void *) (*commentDeps)[j]);
		}
		free(commentDeps);
	}

4770 4771 4772
	destroyPQExpBuffer(query);
	destroyPQExpBuffer(q);
	destroyPQExpBuffer(delq);
4773 4774
}

4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785
/*
 * getAttrName: extract the correct name for an attribute
 *
 * The array tblInfo->attnames[] only provides names of user attributes;
 * if a system attribute number is supplied, we have to fake it.
 * We also do a little bit of bounds checking for safety's sake.
 */
static const char *
getAttrName(int attrnum, TableInfo *tblInfo)
{
	if (attrnum > 0 && attrnum <= tblInfo->numatts)
4786
		return tblInfo->attnames[attrnum - 1];
4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803
	switch (attrnum)
	{
		case SelfItemPointerAttributeNumber:
			return "ctid";
		case ObjectIdAttributeNumber:
			return "oid";
		case MinTransactionIdAttributeNumber:
			return "xmin";
		case MinCommandIdAttributeNumber:
			return "cmin";
		case MaxTransactionIdAttributeNumber:
			return "xmax";
		case MaxCommandIdAttributeNumber:
			return "cmax";
		case TableOidAttributeNumber:
			return "tableoid";
	}
4804
	write_msg(NULL, "getAttrName(): invalid column number %d for table %s\n",
4805
			  attrnum, tblInfo->relname);
4806
	exit_nicely();
4807 4808 4809
	return NULL;				/* keep compiler quiet */
}

4810
/*
4811
 * dumpIndexes:
4812
 *	  write out to fout all the user-defined indexes for dumpable tables
4813
 */
4814
void
4815
dumpIndexes(Archive *fout, TableInfo *tblinfo, int numTables)
4816
{
4817 4818 4819
	int			i,
				j;
	PQExpBuffer query = createPQExpBuffer();
4820 4821
	PQExpBuffer q = createPQExpBuffer();
	PQExpBuffer delq = createPQExpBuffer();
4822 4823 4824 4825 4826 4827 4828 4829
	PGresult   *res;
	int			ntups;
	int			i_indexreloid;
	int			i_indexrelname;
	int			i_indexdef;
	int			i_indisprimary;
	int			i_indkey;
	int			i_indnkeys;
4830

4831
	for (i = 0; i < numTables; i++)
4832
	{
4833
		TableInfo  *tbinfo = &tblinfo[i];
4834

4835 4836
		/* Only plain tables have indexes */
		if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4837 4838
			continue;

4839 4840
		if (!tbinfo->dump)
			continue;
4841

4842 4843
		/* Make sure we are in proper schema so indexdef is right */
		selectSourceSchema(tbinfo->relnamespace->nspname);
4844

4845
		resetPQExpBuffer(query);
4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870
		if (g_fout->remoteVersion >= 70300)
			appendPQExpBuffer(query,
							  "SELECT i.indexrelid as indexreloid, "
							  "t.relname as indexrelname, "
							  "pg_catalog.pg_get_indexdef(i.indexrelid) as indexdef, "
							  "i.indisprimary, i.indkey, "
							  "t.relnatts as indnkeys "
							  "FROM pg_catalog.pg_index i, "
							  "pg_catalog.pg_class t "
							  "WHERE t.oid = i.indexrelid "
							  "AND i.indrelid = '%s'::pg_catalog.oid "
							  "ORDER BY indexrelname",
							  tbinfo->oid);
		else
			appendPQExpBuffer(query,
							  "SELECT i.indexrelid as indexreloid, "
							  "t.relname as indexrelname, "
							  "pg_get_indexdef(i.indexrelid) as indexdef, "
							  "i.indisprimary, i.indkey, "
							  "t.relnatts as indnkeys "
							  "FROM pg_index i, pg_class t "
							  "WHERE t.oid = i.indexrelid "
							  "AND i.indrelid = '%s'::oid "
							  "ORDER BY indexrelname",
							  tbinfo->oid);
4871

4872 4873 4874 4875 4876 4877 4878
		res = PQexec(g_conn, query->data);
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
			write_msg(NULL, "query to obtain list of indexes failed: %s", PQerrorMessage(g_conn));
			exit_nicely();
		}
4879

4880
		ntups = PQntuples(res);
4881

4882 4883 4884 4885 4886 4887
		i_indexreloid = PQfnumber(res, "indexreloid");
		i_indexrelname = PQfnumber(res, "indexrelname");
		i_indexdef = PQfnumber(res, "indexdef");
		i_indisprimary = PQfnumber(res, "indisprimary");
		i_indkey = PQfnumber(res, "indkey");
		i_indnkeys = PQfnumber(res, "indnkeys");
4888

4889
		for (j = 0; j < ntups; j++)
4890
		{
4891 4892 4893 4894 4895 4896 4897 4898 4899
			const char *indexreloid = PQgetvalue(res, j, i_indexreloid);
			const char *indexrelname = PQgetvalue(res, j, i_indexrelname);
			const char *indexdef = PQgetvalue(res, j, i_indexdef);
			const char *indisprimary = PQgetvalue(res, j, i_indisprimary);

			resetPQExpBuffer(q);
			resetPQExpBuffer(delq);

			if (strcmp(indisprimary, "t") == 0)
4900
			{
4901 4902 4903 4904 4905 4906 4907
				/* Handle PK indexes specially */
				int indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
				char **indkeys = (char **) malloc(indnkeys * sizeof(char *));
				int			k;

				parseNumericArray(PQgetvalue(res, j, i_indkey),
								  indkeys, indnkeys);
4908

4909 4910 4911 4912
				appendPQExpBuffer(q, "ALTER TABLE %s ADD ",
								  fmtId(tbinfo->relname, force_quotes));
				appendPQExpBuffer(q, "CONSTRAINT %s PRIMARY KEY (",
								  fmtId(indexrelname, force_quotes));
4913

4914
				for (k = 0; k < indnkeys; k++)
4915
				{
4916 4917 4918 4919 4920 4921 4922 4923 4924 4925
					int			indkey = atoi(indkeys[k]);
					const char *attname;

					if (indkey == InvalidAttrNumber)
						break;
					attname = getAttrName(indkey, tbinfo);

					appendPQExpBuffer(q, "%s%s",
									  (k == 0) ? "" : ", ",
									  fmtId(attname, force_quotes));
4926
				}
4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944

				appendPQExpBuffer(q, ");\n");

				ArchiveEntry(fout, indexreloid,
							 indexrelname,
							 tbinfo->relnamespace->nspname,
							 tbinfo->usename,
							 "CONSTRAINT", NULL,
							 q->data, "",
							 NULL, NULL, NULL);

				free(indkeys);
			}
			else
			{
				/* Plain secondary index */
				appendPQExpBuffer(q, "%s;\n", indexdef);

4945 4946 4947 4948
				/* DROP must be fully qualified in case same name appears in pg_catalog */
				appendPQExpBuffer(delq, "DROP INDEX %s.",
								  fmtId(tbinfo->relnamespace->nspname, force_quotes));
				appendPQExpBuffer(delq, "%s;\n",
4949 4950 4951 4952 4953 4954 4955 4956 4957
								  fmtId(indexrelname, force_quotes));

				ArchiveEntry(fout, indexreloid,
							 indexrelname,
							 tbinfo->relnamespace->nspname,
							 tbinfo->usename,
							 "INDEX", NULL,
							 q->data, delq->data,
							 NULL, NULL, NULL);
4958
			}
4959 4960 4961 4962 4963 4964 4965 4966 4967

			/* Dump Index Comments */
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "INDEX %s",
							  fmtId(indexrelname, force_quotes));
			dumpComment(fout, q->data,
						tbinfo->relnamespace->nspname,
						tbinfo->usename,
						indexreloid, "pg_class", 0, NULL);
4968
		}
4969 4970

		PQclear(res);
4971
	}
4972 4973 4974 4975

	destroyPQExpBuffer(query);
	destroyPQExpBuffer(q);
	destroyPQExpBuffer(delq);
4976 4977
}

4978 4979 4980 4981
/*
 * setMaxOid -
 * find the maximum oid and generate a COPY statement to set it
*/
4982

4983
static void
B
Bruce Momjian 已提交
4984
setMaxOid(Archive *fout)
4985
{
B
Bruce Momjian 已提交
4986 4987
	PGresult   *res;
	Oid			max_oid;
B
Bruce Momjian 已提交
4988
	char		sql[1024];
4989

4990
	res = PQexec(g_conn, "CREATE TEMPORARY TABLE pgdump_oid (dummy integer)");
4991 4992 4993
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
4994
		write_msg(NULL, "could not create pgdump_oid table: %s", PQerrorMessage(g_conn));
4995
		exit_nicely();
4996 4997
	}
	PQclear(res);
4998
	res = PQexec(g_conn, "INSERT INTO pgdump_oid VALUES (0)");
4999 5000 5001
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
5002
		write_msg(NULL, "could not insert into pgdump_oid table: %s", PQerrorMessage(g_conn));
5003
		exit_nicely();
5004
	}
5005
	max_oid = PQoidValue(res);
5006 5007
	if (max_oid == 0)
	{
5008
		write_msg(NULL, "inserted invalid oid\n");
5009
		exit_nicely();
5010 5011
	}
	PQclear(res);
5012
	res = PQexec(g_conn, "DROP TABLE pgdump_oid;");
5013 5014 5015
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
5016
		write_msg(NULL, "could not drop pgdump_oid table: %s", PQerrorMessage(g_conn));
5017
		exit_nicely();
5018 5019 5020
	}
	PQclear(res);
	if (g_verbose)
5021
		write_msg(NULL, "maximum system oid is %u\n", max_oid);
5022
	snprintf(sql, 1024,
5023
			 "CREATE TEMPORARY TABLE pgdump_oid (dummy integer);\n"
5024
			 "COPY pgdump_oid WITH OIDS FROM stdin;\n"
5025
			 "%u\t0\n"
5026 5027 5028
			 "\\.\n"
			 "DROP TABLE pgdump_oid;\n",
			 max_oid);
B
Bruce Momjian 已提交
5029

5030 5031 5032 5033
	ArchiveEntry(fout, "0", "Max OID", NULL, "",
				 "<Init>", NULL,
				 sql, "",
				 NULL, NULL, NULL);
5034
}
5035 5036 5037

/*
 * findLastBuiltInOid -
5038
 * find the last built in oid
5039 5040
 * we do this by retrieving datlastsysoid from the pg_database entry for this database,
 */
5041

5042
static Oid
5043
findLastBuiltinOid_V71(const char *dbname)
5044
{
B
Bruce Momjian 已提交
5045
	PGresult   *res;
5046
	int			ntups;
5047
	Oid			last_oid;
5048 5049 5050
	PQExpBuffer query = createPQExpBuffer();

	resetPQExpBuffer(query);
5051
	appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
5052
	formatStringLiteral(query, dbname, CONV_ALL);
5053

5054
	res = PQexec(g_conn, query->data);
5055 5056 5057
	if (res == NULL ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
5058
		write_msg(NULL, "error in finding the last system oid: %s", PQerrorMessage(g_conn));
5059
		exit_nicely();
5060 5061
	}
	ntups = PQntuples(res);
5062
	if (ntups < 1)
5063
	{
5064
		write_msg(NULL, "missing pg_database entry for this database\n");
5065
		exit_nicely();
5066 5067 5068
	}
	if (ntups > 1)
	{
5069
		write_msg(NULL, "found more than one pg_database entry for this database\n");
5070
		exit_nicely();
5071
	}
5072
	last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
5073
	PQclear(res);
5074
	destroyPQExpBuffer(query);
5075
	return last_oid;
5076 5077
}

5078 5079 5080 5081 5082 5083 5084
/*
 * findLastBuiltInOid -
 * find the last built in oid
 * we do this by looking up the oid of 'template1' in pg_database,
 * this is probably not foolproof but comes close
*/

5085
static Oid
5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096
findLastBuiltinOid_V70(void)
{
	PGresult   *res;
	int			ntups;
	int			last_oid;

	res = PQexec(g_conn,
			  "SELECT oid from pg_database where datname = 'template1'");
	if (res == NULL ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
5097
		write_msg(NULL, "error in finding the template1 database: %s", PQerrorMessage(g_conn));
5098
		exit_nicely();
5099 5100 5101 5102
	}
	ntups = PQntuples(res);
	if (ntups < 1)
	{
5103
		write_msg(NULL, "could not find template1 database entry in the pg_database table\n");
5104
		exit_nicely();
5105 5106 5107
	}
	if (ntups > 1)
	{
5108
		write_msg(NULL, "found more than one template1 database entry in the pg_database table\n");
5109
		exit_nicely();
5110 5111 5112 5113 5114
	}
	last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
	PQclear(res);
	return last_oid;
}
5115

5116
static void
5117 5118
dumpOneSequence(Archive *fout, TableInfo *tbinfo,
				const bool schemaOnly, const bool dataOnly)
5119
{
5120
	PGresult   *res;
5121 5122 5123 5124 5125 5126
	char	   *last,
			   *incby,
			   *maxv,
			   *minv,
			   *cache;
	bool		cycled,
B
Bruce Momjian 已提交
5127
				called;
5128
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
5129
	PQExpBuffer delqry = createPQExpBuffer();
5130

5131 5132 5133
	/* Make sure we are in proper schema */
	selectSourceSchema(tbinfo->relnamespace->nspname);

B
Hi, all  
Bruce Momjian 已提交
5134
	appendPQExpBuffer(query,
5135
			"SELECT sequence_name, last_value, increment_by, max_value, "
5136
				  "min_value, cache_value, is_cycled, is_called from %s",
5137
					  fmtId(tbinfo->relname, force_quotes));
5138

B
Hi, all  
Bruce Momjian 已提交
5139
	res = PQexec(g_conn, query->data);
5140 5141
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
5142
		write_msg(NULL, "query to get data of sequence \"%s\" failed: %s", tbinfo->relname, PQerrorMessage(g_conn));
5143
		exit_nicely();
5144 5145 5146 5147
	}

	if (PQntuples(res) != 1)
	{
5148
		write_msg(NULL, "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
5149
				  tbinfo->relname, PQntuples(res));
5150
		exit_nicely();
5151 5152
	}

5153 5154
	/* Disable this check: it fails if sequence has been renamed */
#ifdef NOT_USED
5155
	if (strcmp(PQgetvalue(res, 0, 0), tbinfo->relname) != 0)
5156
	{
5157
		write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
5158
				  tbinfo->relname, PQgetvalue(res, 0, 0));
5159
		exit_nicely();
5160
	}
5161
#endif
5162

5163 5164 5165 5166 5167 5168 5169
	last = PQgetvalue(res, 0, 1);
	incby = PQgetvalue(res, 0, 2);
	maxv = PQgetvalue(res, 0, 3);
	minv = PQgetvalue(res, 0, 4);
	cache = PQgetvalue(res, 0, 5);
	cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
	called = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
5170

5171
	/*
B
Bruce Momjian 已提交
5172 5173
	 * The logic we use for restoring sequences is as follows: -   Add a
	 * basic CREATE SEQUENCE statement (use last_val for start if called
5174
	 * is false, else use min_val for start_val).
5175
	 *
5176 5177
	 * Add a 'SETVAL(seq, last_val, iscalled)' at restore-time iff we load
	 * data
5178
	 */
5179

5180 5181 5182
	if (!dataOnly)
	{
		resetPQExpBuffer(delqry);
5183 5184 5185 5186 5187

		/* DROP must be fully qualified in case same name appears in pg_catalog */
		appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
						  fmtId(tbinfo->relnamespace->nspname, force_quotes));
		appendPQExpBuffer(delqry, "%s;\n",
5188
						  fmtId(tbinfo->relname, force_quotes));
5189

5190 5191
		resetPQExpBuffer(query);
		appendPQExpBuffer(query,
5192 5193
						  "CREATE SEQUENCE %s start %s increment %s "
						  "maxvalue %s minvalue %s cache %s%s;\n",
5194
						  fmtId(tbinfo->relname, force_quotes),
5195
						  (called ? minv : last),
5196
						  incby, maxv, minv, cache,
5197
						  (cycled ? " cycle" : ""));
5198

5199 5200 5201 5202 5203
		ArchiveEntry(fout, tbinfo->oid, tbinfo->relname,
					 tbinfo->relnamespace->nspname, tbinfo->usename,
					 "SEQUENCE", NULL,
					 query->data, delqry->data,
					 NULL, NULL, NULL);
5204
	}
5205

5206 5207 5208
	if (!schemaOnly)
	{
		resetPQExpBuffer(query);
5209
		appendPQExpBuffer(query, "SELECT pg_catalog.setval (");
5210
		formatStringLiteral(query, fmtId(tbinfo->relname, force_quotes), CONV_ALL);
5211 5212
		appendPQExpBuffer(query, ", %s, %s);\n",
						  last, (called ? "true" : "false"));
5213

5214 5215 5216 5217 5218
		ArchiveEntry(fout, tbinfo->oid, tbinfo->relname,
					 tbinfo->relnamespace->nspname, tbinfo->usename,
					 "SEQUENCE SET", NULL,
					 query->data, "" /* Del */ ,
					 NULL, NULL, NULL);
5219
	}
B
Bruce,  
Bruce Momjian 已提交
5220

5221 5222 5223
	if (!dataOnly)
	{
		/* Dump Sequence Comments */
B
Bruce,  
Bruce Momjian 已提交
5224

5225
		resetPQExpBuffer(query);
5226 5227 5228 5229
		appendPQExpBuffer(query, "SEQUENCE %s", fmtId(tbinfo->relname, force_quotes));
		dumpComment(fout, query->data,
					tbinfo->relnamespace->nspname, tbinfo->usename,
					tbinfo->oid, "pg_class", 0, NULL);
5230
	}
5231

5232 5233
	PQclear(res);

5234 5235
	destroyPQExpBuffer(query);
	destroyPQExpBuffer(delqry);
5236
}
V
Vadim B. Mikheev 已提交
5237 5238


5239
static void
5240
dumpTriggers(Archive *fout, TableInfo *tblinfo, int numTables)
V
Vadim B. Mikheev 已提交
5241
{
5242 5243
	int			i,
				j;
5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259
	PQExpBuffer query = createPQExpBuffer();
	PQExpBuffer delqry = createPQExpBuffer();
	PGresult   *res;
	int			i_tgoid,
				i_tgname,
				i_tgfname,
				i_tgtype,
				i_tgnargs,
				i_tgargs,
				i_tgisconstraint,
				i_tgconstrname,
				i_tgdeferrable,
				i_tgconstrrelid,
				i_tgconstrrelname,
				i_tginitdeferred;
	int			ntups;
5260

V
Vadim B. Mikheev 已提交
5261 5262
	for (i = 0; i < numTables; i++)
	{
5263 5264 5265
		TableInfo	   *tbinfo = &tblinfo[i];

		if (tbinfo->ntrig == 0 || !tbinfo->dump)
V
Vadim B. Mikheev 已提交
5266
			continue;
5267

5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278
		if (g_verbose)
			write_msg(NULL, "dumping triggers for table %s\n",
					  tbinfo->relname);

		/* select table schema to ensure regproc name is qualified if needed */
		selectSourceSchema(tbinfo->relnamespace->nspname);

		resetPQExpBuffer(query);
		if (g_fout->remoteVersion >= 70300)
		{
			appendPQExpBuffer(query,
5279 5280
							  "SELECT tgname, "
							  "tgfoid::pg_catalog.regproc as tgfname, "
5281 5282 5283
							  "tgtype, tgnargs, tgargs, "
							  "tgisconstraint, tgconstrname, tgdeferrable, "
							  "tgconstrrelid, tginitdeferred, oid, "
5284 5285 5286
							  "tgconstrrelid::pg_catalog.regclass as tgconstrrelname "
							  "from pg_catalog.pg_trigger "
							  "where tgrelid = '%s'::pg_catalog.oid",
5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329
							  tbinfo->oid);
		}
		else
		{
			appendPQExpBuffer(query,
							  "SELECT tgname, tgfoid::regproc as tgfname, "
							  "tgtype, tgnargs, tgargs, "
							  "tgisconstraint, tgconstrname, tgdeferrable, "
							  "tgconstrrelid, tginitdeferred, oid, "
							  "(select relname from pg_class where oid = tgconstrrelid) "
							  "		as tgconstrrelname "
							  "from pg_trigger "
							  "where tgrelid = '%s'::oid",
							  tbinfo->oid);
		}
		res = PQexec(g_conn, query->data);
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
			write_msg(NULL, "query to obtain list of triggers failed: %s", PQerrorMessage(g_conn));
			exit_nicely();
		}
		ntups = PQntuples(res);
		if (ntups != tbinfo->ntrig)
		{
			write_msg(NULL, "expected %d triggers on table \"%s\" but found %d\n",
					  tbinfo->ntrig, tbinfo->relname, ntups);
			exit_nicely();
		}
		i_tgname = PQfnumber(res, "tgname");
		i_tgfname = PQfnumber(res, "tgfname");
		i_tgtype = PQfnumber(res, "tgtype");
		i_tgnargs = PQfnumber(res, "tgnargs");
		i_tgargs = PQfnumber(res, "tgargs");
		i_tgoid = PQfnumber(res, "oid");
		i_tgisconstraint = PQfnumber(res, "tgisconstraint");
		i_tgconstrname = PQfnumber(res, "tgconstrname");
		i_tgdeferrable = PQfnumber(res, "tgdeferrable");
		i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
		i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
		i_tginitdeferred = PQfnumber(res, "tginitdeferred");

		for (j = 0; j < ntups; j++)
V
Vadim B. Mikheev 已提交
5330
		{
5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359
			const char *tgoid = PQgetvalue(res, j, i_tgoid);
			char	   *tgname = PQgetvalue(res, j, i_tgname);
			const char *tgfname = PQgetvalue(res, j, i_tgfname);
			int2		tgtype = atoi(PQgetvalue(res, j, i_tgtype));
			int			tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
			const char *tgargs = PQgetvalue(res, j, i_tgargs);
			int			tgisconstraint;
			int			tgdeferrable;
			int			tginitdeferred;
			char	   *tgconstrrelid;
			const char *p;
			int			findx;

			if (strcmp(PQgetvalue(res, j, i_tgisconstraint), "f") == 0)
				tgisconstraint = 0;
			else
				tgisconstraint = 1;

			if (strcmp(PQgetvalue(res, j, i_tgdeferrable), "f") == 0)
				tgdeferrable = 0;
			else
				tgdeferrable = 1;

			if (strcmp(PQgetvalue(res, j, i_tginitdeferred), "f") == 0)
				tginitdeferred = 0;
			else
				tginitdeferred = 1;

			resetPQExpBuffer(delqry);
5360
			/* DROP must be fully qualified in case same name appears in pg_catalog */
5361 5362
			appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
							  fmtId(tgname, force_quotes));
5363 5364 5365
			appendPQExpBuffer(delqry, "ON %s.",
							  fmtId(tbinfo->relnamespace->nspname, force_quotes));
			appendPQExpBuffer(delqry, "%s;\n",
5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503
							  fmtId(tbinfo->relname, force_quotes));

			resetPQExpBuffer(query);
			if (tgisconstraint)
			{
				appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
				appendPQExpBuffer(query, fmtId(PQgetvalue(res, j, i_tgconstrname), force_quotes));
			}
			else
			{
				appendPQExpBuffer(query, "CREATE TRIGGER ");
				appendPQExpBuffer(query, fmtId(tgname, force_quotes));
			}
			appendPQExpBufferChar(query, ' ');
			/* Trigger type */
			findx = 0;
			if (TRIGGER_FOR_BEFORE(tgtype))
				appendPQExpBuffer(query, "BEFORE");
			else
				appendPQExpBuffer(query, "AFTER");
			if (TRIGGER_FOR_INSERT(tgtype))
			{
				appendPQExpBuffer(query, " INSERT");
				findx++;
			}
			if (TRIGGER_FOR_DELETE(tgtype))
			{
				if (findx > 0)
					appendPQExpBuffer(query, " OR DELETE");
				else
					appendPQExpBuffer(query, " DELETE");
				findx++;
			}
			if (TRIGGER_FOR_UPDATE(tgtype))
			{
				if (findx > 0)
					appendPQExpBuffer(query, " OR UPDATE");
				else
					appendPQExpBuffer(query, " UPDATE");
			}
			appendPQExpBuffer(query, " ON %s ",
							  fmtId(tbinfo->relname, force_quotes));

			if (tgisconstraint)
			{
				tgconstrrelid = PQgetvalue(res, j, i_tgconstrrelid);

				if (strcmp(tgconstrrelid, "0") != 0)
				{

					if (PQgetisnull(res, j, i_tgconstrrelname))
					{
						write_msg(NULL, "query produced NULL referenced table name for foreign key trigger \"%s\" on table \"%s\" (oid of table: %s)\n",
								  tgname, tbinfo->relname, tgconstrrelid);
						exit_nicely();
					}

					/* If we are using regclass, name is already quoted */
					if (g_fout->remoteVersion >= 70300)
						appendPQExpBuffer(query, " FROM %s",
										  PQgetvalue(res, j, i_tgconstrrelname));
					else
						appendPQExpBuffer(query, " FROM %s",
										  fmtId(PQgetvalue(res, j, i_tgconstrrelname), force_quotes));
				}
				if (!tgdeferrable)
					appendPQExpBuffer(query, " NOT");
				appendPQExpBuffer(query, " DEFERRABLE INITIALLY ");
				if (tginitdeferred)
					appendPQExpBuffer(query, "DEFERRED");
				else
					appendPQExpBuffer(query, "IMMEDIATE");

			}

			appendPQExpBuffer(query, " FOR EACH ROW");
			/* In 7.3, result of regproc is already quoted */
			if (g_fout->remoteVersion >= 70300)
				appendPQExpBuffer(query, " EXECUTE PROCEDURE %s (",
								  tgfname);
			else
				appendPQExpBuffer(query, " EXECUTE PROCEDURE %s (",
								  fmtId(tgfname, force_quotes));
			for (findx = 0; findx < tgnargs; findx++)
			{
				const char *s;

				for (p = tgargs;;)
				{
					p = strchr(p, '\\');
					if (p == NULL)
					{
						write_msg(NULL, "bad argument string (%s) for trigger \"%s\" on table \"%s\"\n",
								  PQgetvalue(res, j, i_tgargs),
								  tgname,
								  tbinfo->relname);
						exit_nicely();
					}
					p++;
					if (*p == '\\')
					{
						p++;
						continue;
					}
					if (p[0] == '0' && p[1] == '0' && p[2] == '0')
						break;
				}
				p--;
				appendPQExpBufferChar(query, '\'');
				for (s = tgargs; s < p;)
				{
					if (*s == '\'')
						appendPQExpBufferChar(query, '\\');
					appendPQExpBufferChar(query, *s++);
				}
				appendPQExpBufferChar(query, '\'');
				appendPQExpBuffer(query, (findx < tgnargs - 1) ? ", " : "");
				tgargs = p + 4;
			}
			appendPQExpBuffer(query, ");\n");

			ArchiveEntry(fout, tgoid,
						 tgname,
						 tbinfo->relnamespace->nspname,
						 tbinfo->usename,
						 "TRIGGER", NULL,
						 query->data, delqry->data,
						 NULL, NULL, NULL);

			resetPQExpBuffer(query);
			appendPQExpBuffer(query, "TRIGGER %s ",
							  fmtId(tgname, force_quotes));
			appendPQExpBuffer(query, "ON %s",
							  fmtId(tbinfo->relname, force_quotes));

			dumpComment(fout, query->data,
						tbinfo->relnamespace->nspname, tbinfo->usename,
						tgoid, "pg_trigger", 0, NULL);
V
Vadim B. Mikheev 已提交
5504
		}
5505 5506

		PQclear(res);
V
Vadim B. Mikheev 已提交
5507
	}
5508 5509 5510

	destroyPQExpBuffer(query);
	destroyPQExpBuffer(delqry);
V
Vadim B. Mikheev 已提交
5511
}
5512 5513


5514
static void
5515
dumpRules(Archive *fout, TableInfo *tblinfo, int numTables)
5516
{
B
Bruce Momjian 已提交
5517 5518 5519 5520
	PGresult   *res;
	int			nrules;
	int			i,
				t;
5521
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
5522
	int			i_definition;
5523 5524
	int			i_oid;
	int			i_rulename;
5525 5526

	if (g_verbose)
5527
		write_msg(NULL, "dumping out rules\n");
5528 5529 5530 5531 5532 5533

	/*
	 * For each table we dump
	 */
	for (t = 0; t < numTables; t++)
	{
5534 5535 5536
		TableInfo	   *tbinfo = &tblinfo[t];

		if (!tbinfo->hasrules || !tbinfo->dump)
5537 5538
			continue;

5539 5540 5541
		/* Make sure we are in proper schema */
		selectSourceSchema(tbinfo->relnamespace->nspname);

5542
		/*
5543
		 * Get all rules defined for this table, except view select rules
5544
		 */
B
Hi, all  
Bruce Momjian 已提交
5545
		resetPQExpBuffer(query);
5546

5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558
		if (g_fout->remoteVersion >= 70300)
		{
			appendPQExpBuffer(query,
							  "SELECT pg_catalog.pg_get_ruledef(oid) AS definition,"
							  " oid, rulename "
							  "FROM pg_catalog.pg_rewrite "
							  "WHERE ev_class = '%s'::pg_catalog.oid "
							  "AND rulename != '_RETURN' "
							  "ORDER BY oid",
							  tbinfo->oid);
		}
		else
5559 5560 5561 5562 5563 5564 5565 5566 5567
		{
			/*
			 * We include pg_rules in the cross since it filters out all view
			 * rules (pjw 15-Sep-2000).
			 */
			appendPQExpBuffer(query, "SELECT definition,"
							  "   pg_rewrite.oid, pg_rewrite.rulename "
							  "FROM pg_rewrite, pg_class, pg_rules "
							  "WHERE pg_class.relname = ");
5568
			formatStringLiteral(query, tbinfo->relname, CONV_ALL);
5569 5570 5571 5572 5573 5574 5575
			appendPQExpBuffer(query,
							  "    AND pg_rewrite.ev_class = pg_class.oid "
							  "    AND pg_rules.tablename = pg_class.relname "
							  "    AND pg_rules.rulename = pg_rewrite.rulename "
							  "ORDER BY pg_rewrite.oid");
		}

B
Hi, all  
Bruce Momjian 已提交
5576
		res = PQexec(g_conn, query->data);
5577 5578 5579
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
5580
			write_msg(NULL, "query to get rules associated with table \"%s\" failed: %s",
5581
					  tbinfo->relname, PQerrorMessage(g_conn));
5582
			exit_nicely();
5583 5584 5585 5586
		}

		nrules = PQntuples(res);
		i_definition = PQfnumber(res, "definition");
B
Bruce,  
Bruce Momjian 已提交
5587 5588
		i_oid = PQfnumber(res, "oid");
		i_rulename = PQfnumber(res, "rulename");
5589 5590 5591 5592

		/*
		 * Dump them out
		 */
B
Bruce,  
Bruce Momjian 已提交
5593

5594 5595
		for (i = 0; i < nrules; i++)
		{
5596 5597 5598 5599 5600 5601 5602 5603
			ArchiveEntry(fout, PQgetvalue(res, i, i_oid),
						 PQgetvalue(res, i, i_rulename),
						 tbinfo->relnamespace->nspname,
						 tbinfo->usename,
						 "RULE", NULL,
						 PQgetvalue(res, i, i_definition),
						 "",	/* Del */
						 NULL, NULL, NULL);
5604

B
Bruce,  
Bruce Momjian 已提交
5605 5606 5607 5608
			/* Dump rule comments */

			resetPQExpBuffer(query);
			appendPQExpBuffer(query, "RULE %s", fmtId(PQgetvalue(res, i, i_rulename), force_quotes));
5609 5610 5611 5612 5613
			appendPQExpBuffer(query, " ON %s", fmtId(tbinfo->relname, force_quotes));
			dumpComment(fout, query->data,
						tbinfo->relnamespace->nspname,
						tbinfo->usename,
						PQgetvalue(res, i, i_oid), "pg_rewrite", 0, NULL);
5614

B
Bruce,  
Bruce Momjian 已提交
5615 5616
		}

5617 5618
		PQclear(res);
	}
5619 5620

	destroyPQExpBuffer(query);
5621
}
5622 5623 5624 5625 5626

/*
 * selectSourceSchema - make the specified schema the active search path
 * in the source database.
 *
5627 5628 5629 5630 5631 5632 5633
 * NB: pg_catalog is explicitly searched after the specified schema;
 * so user names are only qualified if they are cross-schema references,
 * and system names are only qualified if they conflict with a user name
 * in the current schema.
 *
 * Whenever the selected schema is not pg_catalog, be careful to qualify
 * references to system catalogs and types in our emitted commands!
5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654
 */
static void
selectSourceSchema(const char *schemaName)
{
	static char	   *curSchemaName = NULL;
	PQExpBuffer query;
	PGresult   *res;

	/* Not relevant if fetching from pre-7.3 DB */
	if (g_fout->remoteVersion < 70300)
		return;
	/* Ignore null schema names */
	if (schemaName == NULL || *schemaName == '\0')
		return;
	/* Optimize away repeated selection of same schema */
	if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
		return;

	query = createPQExpBuffer();
	appendPQExpBuffer(query, "SET search_path = %s",
					  fmtId(schemaName, force_quotes));
5655 5656
	if (strcmp(schemaName, "pg_catalog") != 0)
		appendPQExpBuffer(query, ", pg_catalog");
5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700
	res = PQexec(g_conn, query->data);
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		write_msg(NULL, "query to set search_path failed: %s",
				  PQerrorMessage(g_conn));
		exit_nicely();
	}
	PQclear(res);
	destroyPQExpBuffer(query);

	if (curSchemaName)
		free(curSchemaName);
	curSchemaName = strdup(schemaName);
}

/*
 * getFormattedTypeName - retrieve a nicely-formatted type name for the
 * given type name.
 *
 * NB: in 7.3 and up the result may depend on the currently-selected
 * schema; this is why we don't try to cache the names.
 */
static char *
getFormattedTypeName(const char *oid, OidOptions opts)
{
	char	   *result;
	PQExpBuffer query;
	PGresult   *res;
	int			ntups;

	if (atooid(oid) == 0)
	{
		if ((opts & zeroAsOpaque) != 0)
			return strdup(g_opaque_type);
		else if ((opts & zeroAsAny) != 0)
			return strdup("'any'");
		else if ((opts & zeroAsStar) != 0)
			return strdup("*");
		else if ((opts & zeroAsNone) != 0)
			return strdup("NONE");
	}

	query = createPQExpBuffer();
5701 5702 5703 5704 5705 5706
	if (g_fout->remoteVersion >= 70300)
	{
		appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%s'::pg_catalog.oid, NULL)",
						  oid);
	}
	else if (g_fout->remoteVersion >= 70100)
5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736
	{
		appendPQExpBuffer(query, "SELECT format_type('%s'::oid, NULL)",
						  oid);
	}
	else
	{
		appendPQExpBuffer(query, "SELECT typname "
						  "FROM pg_type "
						  "WHERE oid = '%s'::oid",
						  oid);
	}

	res = PQexec(g_conn, query->data);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		write_msg(NULL, "query to obtain type name for %s failed: %s",
				  oid, PQerrorMessage(g_conn));
		exit_nicely();
	}

	/* Expecting a single result only */
	ntups = PQntuples(res);
	if (ntups != 1)
	{
		write_msg(NULL, "Got %d rows instead of one from: %s",
				  ntups, query->data);
		exit_nicely();
	}

5737 5738 5739 5740 5741 5742 5743 5744 5745 5746
	if (g_fout->remoteVersion >= 70100)
	{
		/* already quoted */
		result = strdup(PQgetvalue(res, 0, 0));
	}
	else
	{
		/* may need to quote it */
		result = strdup(fmtId(PQgetvalue(res, 0, 0), false));
	}
5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844

	PQclear(res);
	destroyPQExpBuffer(query);

	return result;
}

/*
 * myFormatType --- local implementation of format_type for use with 7.0.
 */
static char *
myFormatType(const char *typname, int32 typmod)
{
	char	   *result;
	PQExpBuffer buf = createPQExpBuffer();

	/* Show lengths on bpchar and varchar */
	if (!strcmp(typname, "bpchar"))
	{
		int			len = (typmod - VARHDRSZ);

		appendPQExpBuffer(buf, "character");
		if (len > 1)
			appendPQExpBuffer(buf, "(%d)",
							  typmod - VARHDRSZ);
	}
	else if (!strcmp(typname, "varchar"))
	{
		appendPQExpBuffer(buf, "character varying");
		if (typmod != -1)
			appendPQExpBuffer(buf, "(%d)",
							  typmod - VARHDRSZ);
	}
	else if (!strcmp(typname, "numeric"))
	{
		appendPQExpBuffer(buf, "numeric");
		if (typmod != -1)
		{
			int32		tmp_typmod;
			int			precision;
			int			scale;

			tmp_typmod = typmod - VARHDRSZ;
			precision = (tmp_typmod >> 16) & 0xffff;
			scale = tmp_typmod & 0xffff;
			appendPQExpBuffer(buf, "(%d,%d)",
							  precision, scale);
		}
	}

	/*
	 * char is an internal single-byte data type; Let's make sure we force
	 * it through with quotes. - thomas 1998-12-13
	 */
	else if (!strcmp(typname, "char"))
	{
		appendPQExpBuffer(buf, "%s",
						  fmtId(typname, true));
	}
	else
	{
		appendPQExpBuffer(buf, "%s",
						  fmtId(typname, false));
	}

	result = strdup(buf->data);
	destroyPQExpBuffer(buf);

	return result;
}

/*
 * fmtQualifiedId - convert a qualified name to the proper format for
 * the source database.
 *
 * Like fmtId, use the result before calling again.
 */
static const char *
fmtQualifiedId(const char *schema, const char *id)
{
	static PQExpBuffer id_return = NULL;

	if (id_return)				/* first time through? */
		resetPQExpBuffer(id_return);
	else
		id_return = createPQExpBuffer();

	/* Suppress schema name if fetching from pre-7.3 DB */
	if (g_fout->remoteVersion >= 70300 && schema && *schema)
	{
		appendPQExpBuffer(id_return, "%s.",
						  fmtId(schema, force_quotes));
	}
	appendPQExpBuffer(id_return, "%s",
					  fmtId(id, force_quotes));

	return id_return->data;
}