pg_dump.c 97.1 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * pg_dump.c
4
 *	  pg_dump is an utility for dumping out a postgres database
5 6
 * into a script file.
 *
7 8 9 10 11 12 13 14 15 16
 *	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
 *		  indices
 *		  aggregates
 *		  operators
 *		  ACL - grant/revoke
17
 *
18
 * the output script is SQL that is understood by PostgreSQL
19
 *
B
Add:  
Bruce Momjian 已提交
20 21
 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
 * Portions Copyright (c) 1994, Regents of the University of California
22 23 24
 *
 *
 * IDENTIFICATION
25
 *	  $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_dump.c,v 1.153 2000/07/02 15:21:05 petere Exp $
26
 *
27
 * Modifications - 6/10/96 - dave@bensoft.com - version 1.13.dhb
28
 *
29 30 31 32
 *	 Applied 'insert string' patch from "Marc G. Fournier" <scrappy@ki.net>
 *	 Added '-t table' option
 *	 Added '-a' option
 *	 Added '-da' option
33
 *
34 35
 * Modifications - 6/12/96 - dave@bensoft.com - version 1.13.dhb.2
 *
36 37 38
 *	 - Fixed dumpTable output to output lengths for char and varchar types!
 *	 - Added single. quote to twin single quote expansion for 'insert' string
 *	   mode.
39
 *
40 41
 * Modifications - 7/26/96 - asussman@vidya.com
 *
42
 *	 - Fixed ouput lengths for char and varchar type where the length is variable (-1)
43
 *
44 45
 * Modifications - 6/1/97 - igor@sba.miami.edu
 * - Added functions to free allocated memory used for retrieving
46 47
 *	 indices,tables,inheritance,types,functions and aggregates.
 *	 No more leaks reported by Purify.
48 49 50
 *
 *
 * Modifications - 1/26/98 - pjlobo@euitt.upm.es
51
 *		 - Added support for password authentication
52 53 54
 *-------------------------------------------------------------------------
 */

55
#include <unistd.h>				/* for getopt() */
56
#include <ctype.h>
57 58

#include "postgres.h"
59 60 61 62 63 64 65 66 67

#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif

#include "access/attnum.h"
68
#include "access/htup.h"
69
#include "catalog/pg_index.h"
70
#include "catalog/pg_language.h"
V
Vadim B. Mikheev 已提交
71
#include "catalog/pg_trigger.h"
72
#include "catalog/pg_type.h"
73

74
#include "libpq-fe.h"
75
#ifndef HAVE_STRDUP
76 77
#include "strdup.h"
#endif
78 79 80

#include "pg_dump.h"

B
Bruce,  
Bruce Momjian 已提交
81
static void dumpComment(FILE *outfile, const char *target, const char *oid);
82
static void dumpSequence(FILE *fout, TableInfo tbinfo);
B
Bruce Momjian 已提交
83
static void dumpACL(FILE *fout, TableInfo tbinfo);
84
static void dumpTriggers(FILE *fout, const char *tablename,
85
			 TableInfo *tblinfo, int numTables);
86
static void dumpRules(FILE *fout, const char *tablename,
B
Bruce Momjian 已提交
87
		  TableInfo *tblinfo, int numTables);
88 89
static char *checkForQuote(const char *s);
static void clearTableInfo(TableInfo *, int);
90
static void dumpOneFunc(FILE *fout, FuncInfo *finfo, int i,
91
			TypeInfo *tinfo, int numTypes);
92 93
static int	findLastBuiltinOid(void);
static bool isViewRule(char *relname);
94
static void setMaxOid(FILE *fout);
95

96 97
static void AddAcl(char *aclbuf, const char *keyword);
static char *GetPrivileges(const char *s);
98
static void becomeUser(FILE *fout, const char *username);
V
Vadim B. Mikheev 已提交
99

B
Bruce Momjian 已提交
100
extern char *optarg;
101
extern int	optind,
B
Bruce Momjian 已提交
102
			opterr;
103 104

/* global decls */
105
bool		g_verbose;			/* User wants verbose narration of our
B
Bruce Momjian 已提交
106 107 108 109 110 111
								 * activities. */
int			g_last_builtin_oid; /* value of the last builtin oid */
FILE	   *g_fout;				/* the script file */
PGconn	   *g_conn;				/* the database connection */

bool		force_quotes;		/* User wants to suppress double-quotes */
112 113 114 115
bool		dumpData;			/* dump data using proper insert strings */
bool		attrNames;			/* put attr names into insert strings */
bool		schemaOnly;
bool		dataOnly;
116
bool		aclsSkip;
117
bool		dropSchema;
118

B
Bruce Momjian 已提交
119
char		g_opaque_type[10];	/* name for the opaque type */
120 121

/* placeholders for the delimiters for comments */
122 123
char		g_comment_start[10];
char		g_comment_end[10];
124 125 126


static void
127
help(const char *progname)
128
{
P
Peter Eisentraut 已提交
129
	printf("%s dumps a database as a text file.\n\n", progname);
130 131 132
	puts("Usage:");
	printf("  %s [options] dbname\n\n", progname);
	puts("Options:");
B
Hi,  
Bruce Momjian 已提交
133 134

#ifdef HAVE_GETOPT_LONG
135
	puts(
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
	"  -a, --data-only          dump out only the data, not the schema\n"
	   "  -c, --clean              clean (drop) schema prior to create\n"
		 "  -d, --inserts            dump data as INSERT, rather than COPY, commands\n"
		 "  -D, --attribute-inserts  dump data as INSERT commands with attribute names\n"
		 "  -h, --host <hostname>    server host name\n"
		 "  -i, --ignore-version     proceed when database version != pg_dump version\n"
	"  -n, --no-quotes          suppress most quotes around identifiers\n"
	 "  -N, --quotes             enable most quotes around identifiers\n"
		 "  -o, --oids               dump object ids (oids)\n"
		 "  -p, --port <port>        server port number\n"
		 "  -s, --schema-only        dump out only the schema, no data\n"
		 "  -t, --table <table>      dump for this table only\n"
		 "  -u, --password           use password authentication\n"
		 "  -v, --verbose            verbose\n"
		 "  -x, --no-acl             do not dump ACL's (grant/revoke)\n"
		);
B
Hi,  
Bruce Momjian 已提交
152
#else
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
	puts(
		 "  -a                       dump out only the data, no schema\n"
	   "  -c                       clean (drop) schema prior to create\n"
		 "  -d                       dump data as INSERT, rather than COPY, commands\n"
		 "  -D                       dump data as INSERT commands with attribute names\n"
		 "  -h <hostname>            server host name\n"
		 "  -i                       proceed when database version != pg_dump version\n"
	"  -n                       suppress most quotes around identifiers\n"
	 "  -N                       enable most quotes around identifiers\n"
		 "  -o                       dump object ids (oids)\n"
		 "  -p <port>                server port number\n"
		 "  -s                       dump out only the schema, no data\n"
		 "  -t <table>               dump for this table only\n"
		 "  -u                       use password authentication\n"
		 "  -v                       verbose\n"
		 "  -x                       do not dump ACL's (grant/revoke)\n"
		);
B
Hi,  
Bruce Momjian 已提交
170
#endif
171 172
	puts("If no database name is not supplied, then the PGDATABASE environment\nvariable value is used.\n");
	puts("Report bugs to <pgsql-bugs@postgresql.org>.");
173
}
174

175

176 177 178
static void
version(void)
{
179
	puts("pg_dump (PostgreSQL) " PG_VERSION);
180 181 182
	puts("Portions Copyright (c) 1996-2000, PostgreSQL, Inc");
	puts("Portions Copyright (C) 1996 Regents of the University of California");
	puts("Read the file COPYRIGHT to see the usage and distribution terms.");
183 184
}

185

186
static void
187
exit_nicely(PGconn *conn)
188
{
189 190
	PQfinish(conn);
	exit(1);
191 192 193
}


M
Marc G. Fournier 已提交
194 195
/*
 * isViewRule
196
 *				Determine if the relation is a VIEW
M
Marc G. Fournier 已提交
197 198
 *
 */
199
static bool
M
Marc G. Fournier 已提交
200 201
isViewRule(char *relname)
{
B
Bruce Momjian 已提交
202 203
	PGresult   *res;
	int			ntups;
204
	PQExpBuffer query = createPQExpBuffer();
205

B
Hi, all  
Bruce Momjian 已提交
206 207 208 209
	appendPQExpBuffer(query, "select relname from pg_class, pg_rewrite ");
	appendPQExpBuffer(query, "where pg_class.oid = ev_class ");
	appendPQExpBuffer(query, "and pg_rewrite.ev_type = '1' ");
	appendPQExpBuffer(query, "and rulename = '_RET%s'", relname);
210

B
Hi, all  
Bruce Momjian 已提交
211
	res = PQexec(g_conn, query->data);
212 213 214
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
215
		fprintf(stderr, "isViewRule(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
216 217 218 219 220 221 222
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	PQclear(res);
	return ntups > 0 ? TRUE : FALSE;
M
Marc G. Fournier 已提交
223
}
224

225 226 227 228
#define COPYBUFSIZ		8192


static void
229
dumpClasses_nodumpData(FILE *fout, const char *classname, const bool oids)
230 231
{

232 233 234 235 236
	PGresult   *res;
	char		query[255];
	int			ret;
	bool		copydone;
	char		copybuf[COPYBUFSIZ];
237

238
	if (oids == true)
239
	{
240
		fprintf(fout, "COPY %s WITH OIDS FROM stdin;\n",
241
				fmtId(classname, force_quotes));
242
		sprintf(query, "COPY %s WITH OIDS TO stdout;\n",
243
				fmtId(classname, force_quotes));
244 245 246
	}
	else
	{
247 248
		fprintf(fout, "COPY %s FROM stdin;\n", fmtId(classname, force_quotes));
		sprintf(query, "COPY %s TO stdout;\n", fmtId(classname, force_quotes));
249 250
	}
	res = PQexec(g_conn, query);
251 252
	if (!res ||
		PQresultStatus(res) == PGRES_FATAL_ERROR)
253
	{
254
		fprintf(stderr, "SQL query to dump the contents of Table '%s' "
255 256 257 258 259 260 261 262 263
				"did not execute.  Explanation from backend: '%s'.\n"
				"The query was: '%s'.\n",
				classname, PQerrorMessage(g_conn), query);
		exit_nicely(g_conn);
	}
	else
	{
		if (PQresultStatus(res) != PGRES_COPY_OUT)
		{
264
			fprintf(stderr, "SQL query to dump the contents of Table '%s' "
265 266 267 268 269 270 271 272 273 274 275
					"executed abnormally.\n"
					"PQexec() returned status %d when %d was expected.\n"
					"The query was: '%s'.\n",
				  classname, PQresultStatus(res), PGRES_COPY_OUT, query);
			exit_nicely(g_conn);
		}
		else
		{
			copydone = false;
			while (!copydone)
			{
276
				ret = PQgetline(g_conn, copybuf, COPYBUFSIZ);
277 278 279 280 281 282 283 284 285 286 287 288

				if (copybuf[0] == '\\' &&
					copybuf[1] == '.' &&
					copybuf[2] == '\0')
				{
					copydone = true;	/* don't print this... */
				}
				else
				{
					fputs(copybuf, fout);
					switch (ret)
					{
289 290 291 292 293 294 295 296
						case EOF:
							copydone = true;
							/* FALLTHROUGH */
						case 0:
							fputc('\n', fout);
							break;
						case 1:
							break;
297 298 299 300 301
					}
				}
			}
			fprintf(fout, "\\.\n");
		}
302
		ret = PQendcopy(g_conn);
303 304
		if (ret != 0)
		{
305
			fprintf(stderr, "SQL query to dump the contents of Table '%s' "
306 307 308 309 310
					"did not execute correctly.  After we read all the "
				 "table contents from the backend, PQendcopy() failed.  "
					"Explanation from backend: '%s'.\n"
					"The query was: '%s'.\n",
					classname, PQerrorMessage(g_conn), query);
B
Bruce Momjian 已提交
311
			PQclear(res);
312 313 314
			exit_nicely(g_conn);
		}
	}
315 316 317 318 319
}



static void
B
Bruce Momjian 已提交
320
dumpClasses_dumpData(FILE *fout, const char *classname)
321
{
322 323
	PGresult   *res;
	PQExpBuffer q = createPQExpBuffer();
324 325
	int			tuple;
	int			field;
326
	const char *expsrc;
327

B
Hi, all  
Bruce Momjian 已提交
328 329
	appendPQExpBuffer(q, "SELECT * FROM %s", fmtId(classname, force_quotes));
	res = PQexec(g_conn, q->data);
330 331 332
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
333
		fprintf(stderr, "dumpClasses(): command failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
334 335
		exit_nicely(g_conn);
	}
336
	for (tuple = 0; tuple < PQntuples(res); tuple++)
337
	{
338
		fprintf(fout, "INSERT INTO %s ", fmtId(classname, force_quotes));
339
		if (attrNames == true)
340
		{
B
Hi, all  
Bruce Momjian 已提交
341 342
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "(");
343
			for (field = 0; field < PQnfields(res); field++)
344
			{
345
				if (field > 0)
B
Hi, all  
Bruce Momjian 已提交
346 347
					appendPQExpBuffer(q, ",");
				appendPQExpBuffer(q, fmtId(PQfname(res, field), force_quotes));
348
			}
B
Hi, all  
Bruce Momjian 已提交
349 350
			appendPQExpBuffer(q, ") ");
			fprintf(fout, "%s", q->data);
351
		}
352
		fprintf(fout, "VALUES (");
353
		for (field = 0; field < PQnfields(res); field++)
354
		{
355 356
			if (field > 0)
				fprintf(fout, ",");
357
			if (PQgetisnull(res, tuple, field))
358
			{
359
				fprintf(fout, "NULL");
360 361 362
				continue;
			}
			switch (PQftype(res, field))
363
			{
364 365
				case INT2OID:
				case INT4OID:
366
				case OIDOID:	/* int types */
367
				case FLOAT4OID:
368
				case FLOAT8OID:/* float types */
369 370 371 372 373
					/* These types are printed without quotes */
					fprintf(fout, "%s",
							PQgetvalue(res, tuple, field));
					break;
				default:
374

375 376
					/*
					 * All other types are printed as string literals,
377 378 379
					 * with appropriate escaping of special characters.
					 * Quote mark ' goes to '' per SQL standard, other
					 * stuff goes to \ sequences.
380 381 382 383 384 385 386 387
					 */
					putc('\'', fout);
					expsrc = PQgetvalue(res, tuple, field);
					while (*expsrc)
					{
						char		ch = *expsrc++;

						if (ch == '\\' || ch == '\'')
388
						{
389
							putc(ch, fout);		/* double these */
390
							putc(ch, fout);
391
						}
392 393 394 395 396 397 398 399 400 401 402 403 404
						else if (ch < '\040')
						{
							/* generate octal escape for control chars */
							putc('\\', fout);
							putc(((ch >> 6) & 3) + '0', fout);
							putc(((ch >> 3) & 7) + '0', fout);
							putc((ch & 7) + '0', fout);
						}
						else
							putc(ch, fout);
					}
					putc('\'', fout);
					break;
405
			}
406
		}
407 408 409
		fprintf(fout, ");\n");
	}
	PQclear(res);
410 411 412 413 414 415
}



/*
 * DumpClasses -
416
 *	  dump the contents of all the classes.
417 418
 */
static void
419
dumpClasses(const TableInfo *tblinfo, const int numTables, FILE *fout,
420 421 422
			const char *onlytable, const bool oids)
{

423
	int			i;
B
Bruce Momjian 已提交
424
	char	   *all_only;
425 426 427 428

	if (onlytable == NULL)
		all_only = "all";
	else
429
		all_only = "only";
430 431

	if (g_verbose)
432 433 434
		fprintf(stderr, "%s dumping out the contents of %s %d table%s/sequence%s %s\n",
				g_comment_start, all_only,
				(onlytable == NULL) ? numTables : 1,
435
		  (onlytable == NULL) ? "s" : "", (onlytable == NULL) ? "s" : "",
436
				g_comment_end);
437

V
Vadim B. Mikheev 已提交
438 439 440 441 442 443 444 445 446 447
	/* Dump SEQUENCEs first (if dataOnly) */
	if (dataOnly)
	{
		for (i = 0; i < numTables; i++)
		{
			if (!(tblinfo[i].sequence))
				continue;
			if (!onlytable || (!strcmp(tblinfo[i].relname, onlytable)))
			{
				if (g_verbose)
448
					fprintf(stderr, "%s dumping out schema of sequence '%s' %s\n",
449
					 g_comment_start, tblinfo[i].relname, g_comment_end);
450
				becomeUser(fout, tblinfo[i].usename);
V
Vadim B. Mikheev 已提交
451 452 453 454
				dumpSequence(fout, tblinfo[i]);
			}
		}
	}
455 456 457

	for (i = 0; i < numTables; i++)
	{
458
		const char *classname = tblinfo[i].relname;
459 460 461 462

		/* Skip VIEW relations */
		if (isViewRule(tblinfo[i].relname))
			continue;
463 464

		if (tblinfo[i].sequence)/* already dumped */
V
Vadim B. Mikheev 已提交
465
			continue;
466 467 468 469

		if (!onlytable || (!strcmp(classname, onlytable)))
		{
			if (g_verbose)
470
				fprintf(stderr, "%s dumping out the contents of Table '%s' %s\n",
471 472
						g_comment_start, classname, g_comment_end);

473 474
			becomeUser(fout, tblinfo[i].usename);

475 476 477
			if (!dumpData)
				dumpClasses_nodumpData(fout, classname, oids);
			else
B
Bruce Momjian 已提交
478
				dumpClasses_dumpData(fout, classname);
479
		}
480
	}
481 482 483
}


484 485 486
static void
prompt_for_password(char *username, char *password)
{
487
	char		buf[512];
B
Bruce Momjian 已提交
488
	int			length;
489 490

#ifdef HAVE_TERMIOS_H
B
Bruce Momjian 已提交
491
	struct termios t_orig,
492
				   t;
493 494
#endif

495
	fprintf(stderr, "Username: ");
496
	fflush(stderr);
497
	fgets(username, 100, stdin);
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
	length = strlen(username);
	/* skip rest of the line */
	if (length > 0 && username[length - 1] != '\n')
	{
		do
		{
			fgets(buf, 512, stdin);
		} while (buf[strlen(buf) - 1] != '\n');
	}
	if (length > 0 && username[length - 1] == '\n')
		username[length - 1] = '\0';

#ifdef HAVE_TERMIOS_H
	tcgetattr(0, &t);
	t_orig = t;
	t.c_lflag &= ~ECHO;
	tcsetattr(0, TCSADRAIN, &t);
#endif
516 517
	fprintf(stderr, "Password: ");
	fflush(stderr);
518
	fgets(password, 100, stdin);
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
#ifdef HAVE_TERMIOS_H
	tcsetattr(0, TCSADRAIN, &t_orig);
#endif

	length = strlen(password);
	/* skip rest of the line */
	if (length > 0 && password[length - 1] != '\n')
	{
		do
		{
			fgets(buf, 512, stdin);
		} while (buf[strlen(buf) - 1] != '\n');
	}
	if (length > 0 && password[length - 1] == '\n')
		password[length - 1] = '\0';

535
	fprintf(stderr, "\n\n");
536 537
}

538

539
static void
540
check_database_version(bool ignoreVersion)
541
{
542
	PGresult   *res;
543 544 545
	double      myversion;
	const char *remoteversion_str;
	double      remoteversion;
546

547
	myversion = strtod(PG_VERSION, NULL);
548 549 550 551 552 553 554 555
	res = PQexec(g_conn, "SELECT version()");
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK ||
		PQntuples(res) != 1)
	{
		fprintf(stderr, "check_database_version(): command failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
		exit_nicely(g_conn);
	}
556 557 558 559

	remoteversion_str = PQgetvalue(res, 0, 0);
	remoteversion = strtod(remoteversion_str + 11, NULL);
	if (myversion != remoteversion)
560 561
	{
		fprintf(stderr, "Database version: %s\npg_dump version: %s\n",
562
				remoteversion_str, PG_VERSION);
563 564 565 566 567 568 569 570 571 572 573 574 575
		if (ignoreVersion)
			fprintf(stderr, "Proceeding despite version mismatch.\n");
		else
		{
			fprintf(stderr, "Aborting because of version mismatch.\n"
					"Use --ignore-version if you think it's safe to proceed anyway.\n");
			exit_nicely(g_conn);
		}
	}
	PQclear(res);
}


576
int
577
main(int argc, char **argv)
578
{
B
Bruce Momjian 已提交
579 580 581 582 583 584 585
	int			c;
	const char *progname;
	const char *filename = NULL;
	const char *dbname = NULL;
	const char *pghost = NULL;
	const char *pgport = NULL;
	char	   *tablename = NULL;
586
	bool		oids = false;
B
Bruce Momjian 已提交
587 588
	TableInfo  *tblinfo;
	int			numTables;
589 590
	char		connect_string[512] = "";
	char		tmp_string[128];
591 592
	char		username[100];
	char		password[100];
593
	bool		use_password = false;
594
	bool		ignore_version = false;
595

B
Hi,  
Bruce Momjian 已提交
596 597 598 599
#ifdef HAVE_GETOPT_LONG
	static struct option long_options[] = {
		{"data-only", no_argument, NULL, 'a'},
		{"clean", no_argument, NULL, 'c'},
600
		{"inserts", no_argument, NULL, 'd'},
601
		{"attribute-inserts", no_argument, NULL, 'D'},
B
Hi,  
Bruce Momjian 已提交
602
		{"host", required_argument, NULL, 'h'},
603
		{"ignore-version", no_argument, NULL, 'i'},
B
Hi,  
Bruce Momjian 已提交
604 605
		{"no-quotes", no_argument, NULL, 'n'},
		{"quotes", no_argument, NULL, 'N'},
606
		{"oids", no_argument, NULL, 'o'},
B
Hi,  
Bruce Momjian 已提交
607 608 609 610 611 612 613
		{"port", required_argument, NULL, 'p'},
		{"schema-only", no_argument, NULL, 's'},
		{"table", required_argument, NULL, 't'},
		{"password", no_argument, NULL, 'u'},
		{"verbose", no_argument, NULL, 'v'},
		{"no-acl", no_argument, NULL, 'x'},
		{"help", no_argument, NULL, '?'},
614
		{"version", no_argument, NULL, 'V'}
615
	};
616 617
	int			optindex;

B
Hi,  
Bruce Momjian 已提交
618 619
#endif

620
	g_verbose = false;
621
	force_quotes = true;
622
	dropSchema = false;
623 624 625 626 627

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

628
	dataOnly = schemaOnly = dumpData = attrNames = false;
629

630 631 632 633
	if (!strrchr(argv[0], SEP_CHAR))
		progname = argv[0];
	else
		progname = strrchr(argv[0], SEP_CHAR) + 1;
634

635

B
Hi,  
Bruce Momjian 已提交
636
#ifdef HAVE_GETOPT_LONG
637
	while ((c = getopt_long(argc, argv, "acdDf:h:inNop:st:uvxzV?", long_options, &optindex)) != -1)
B
Hi,  
Bruce Momjian 已提交
638
#else
639
	while ((c = getopt(argc, argv, "acdDf:h:inNop:st:uvxzV?-")) != -1)
B
Hi,  
Bruce Momjian 已提交
640
#endif
641 642 643
	{
		switch (c)
		{
644
			case 'a':			/* Dump data only */
645
				dataOnly = true;
646
				break;
B
Bruce Momjian 已提交
647 648
			case 'c':			/* clean (i.e., drop) schema prior to
								 * create */
649
				dropSchema = true;
650
				break;
651
			case 'd':			/* dump data as proper insert strings */
652
				dumpData = true;
653 654 655
				break;
			case 'D':			/* dump data as proper insert strings with
								 * attr names */
656 657
				dumpData = true;
				attrNames = true;
658
				break;
659
			case 'f':
660 661
				filename = optarg;
				break;
B
Bruce Momjian 已提交
662
			case 'h':			/* server host */
663 664
				pghost = optarg;
				break;
665 666 667
			case 'i':			/* ignore database version mismatch */
				ignore_version = true;
				break;
B
Bruce Momjian 已提交
668 669
			case 'n':			/* Do not force double-quotes on
								 * identifiers */
670
				force_quotes = false;
671
				break;
672
			case 'N':			/* Force double-quotes on identifiers */
673
				force_quotes = true;
674
				break;
675
			case 'o':			/* Dump oids */
676
				oids = true;
677
				break;
678 679 680
			case 'p':			/* server port */
				pgport = optarg;
				break;
681
			case 's':			/* dump schema only */
682
				schemaOnly = true;
683 684
				break;
			case 't':			/* Dump data for this table only */
685
				{
686
					int			i;
687 688

					tablename = strdup(optarg);
B
Bruce Momjian 已提交
689 690 691 692 693

					/*
					 * quoted string? Then strip quotes and preserve
					 * case...
					 */
694 695 696
					if (tablename[0] == '"')
					{
						strcpy(tablename, &tablename[1]);
B
Bruce Momjian 已提交
697 698
						if (*(tablename + strlen(tablename) - 1) == '"')
							*(tablename + strlen(tablename) - 1) = '\0';
699 700 701 702 703
					}
					/* otherwise, convert table name to lowercase... */
					else
					{
						for (i = 0; tablename[i]; i++)
704 705
							if (isascii((int) tablename[i]) &&
								isupper((int) tablename[i]))
706 707
								tablename[i] = tolower(tablename[i]);
					}
708
				}
709
				break;
710 711 712
			case 'u':
				use_password = true;
				break;
713 714
			case 'v':			/* verbose */
				g_verbose = true;
715
				break;
716 717
			case 'x':			/* skip ACL dump */
				aclsSkip = true;
718
				break;
719 720 721 722
			case 'V':
				version();
				exit(0);
				break;
723
			case '?':
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738

				/*
				 * getopt returns '?' on unknown argument. That's not
				 * quite what we want
				 */
				if (strcmp(argv[optind - 1], "-?") == 0 || strcmp(argv[optind - 1], "--help") == 0)
				{
					help(progname);
					exit(1);
				}
				else
				{
					fputs("Try -? for help.\n", stderr);
					exit(1);
				}
739
				break;
740 741 742
#ifndef HAVE_GETOPT_LONG
			case '-':
				fprintf(stderr, "%s was compiled without support for long options.\n"
743
				   "Use -? for help on invocation options.\n", progname);
744 745 746
				exit(1);
				break;
#endif
747
			default:
748 749
				fprintf(stderr, "%s: unknown option -%c\nTry -? for help.\n", progname, c);
				exit(1);
750 751 752
		}
	}

753 754 755
	if (dumpData == true && oids == true)
	{
		fprintf(stderr,
756
				"%s: INSERT's can not set oids, so INSERT and OID options can not be used together.\n",
757
				progname);
758
		exit(1);
759
	}
760

761 762 763 764 765
	/* open the output file */
	if (filename == NULL)
		g_fout = stdout;
	else
	{
766
		g_fout = fopen(filename, PG_BINARY_W);
767 768 769 770 771
		if (g_fout == NULL)
		{
			fprintf(stderr,
				 "%s: could not open output file named %s for writing\n",
					progname, filename);
772
			exit(1);
773 774 775 776 777
		}
	}

	/* find database */
	if (!(dbname = argv[optind]) &&
778
		!(dbname = getenv("PGDATABASE")))
779 780
	{
		fprintf(stderr, "%s: no database name specified\n", progname);
781
		exit(1);
782 783
	}

784 785 786 787 788
	/* g_conn = PQsetdb(pghost, pgport, NULL, NULL, dbname); */
	if (pghost != NULL)
	{
		sprintf(tmp_string, "host=%s ", pghost);
		strcat(connect_string, tmp_string);
789
	}
790 791 792 793
	if (pgport != NULL)
	{
		sprintf(tmp_string, "port=%s ", pgport);
		strcat(connect_string, tmp_string);
794
	}
795 796 797 798
	if (dbname != NULL)
	{
		sprintf(tmp_string, "dbname=%s ", dbname);
		strcat(connect_string, tmp_string);
799
	}
800 801 802 803 804 805 806 807
	if (use_password)
	{
		prompt_for_password(username, password);
		strcat(connect_string, "authtype=password ");
		sprintf(tmp_string, "user=%s ", username);
		strcat(connect_string, tmp_string);
		sprintf(tmp_string, "password=%s ", password);
		strcat(connect_string, tmp_string);
808 809
		MemSet(tmp_string, 0, sizeof(tmp_string));
		MemSet(password, 0, sizeof(password));
810 811
	}
	g_conn = PQconnectdb(connect_string);
812
	MemSet(connect_string, 0, sizeof(connect_string));
813 814 815 816 817 818 819 820
	/* check to see that the backend connection was successfully made */
	if (PQstatus(g_conn) == CONNECTION_BAD)
	{
		fprintf(stderr, "Connection to database '%s' failed.\n", dbname);
		fprintf(stderr, "%s\n", PQerrorMessage(g_conn));
		exit_nicely(g_conn);
	}

821 822 823
	/* check for version mismatch */
	check_database_version(ignore_version);

824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
	/*
	 * Start serializable transaction to dump consistent data
	 */
	{
		PGresult   *res;

		res = PQexec(g_conn, "begin");
		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
		{
			fprintf(stderr, "BEGIN command failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
			exit_nicely(g_conn);
		}
		PQclear(res);
		res = PQexec(g_conn, "set transaction isolation level serializable");
		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
		{
			fprintf(stderr, "SET TRANSACTION command failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
			exit_nicely(g_conn);
		}
		PQclear(res);
	}

846 847
	g_last_builtin_oid = findLastBuiltinOid();

848
	if (oids == true)
849 850 851 852
		setMaxOid(g_fout);
	if (!dataOnly)
	{
		if (g_verbose)
853
			fprintf(stderr, "%s last builtin oid is %u %s\n",
854
					g_comment_start, g_last_builtin_oid, g_comment_end);
855
		tblinfo = dumpSchema(g_fout, &numTables, tablename, aclsSkip);
856 857
	}
	else
858
		tblinfo = dumpSchema(NULL, &numTables, tablename, aclsSkip);
859

860 861
	if (!schemaOnly)
	{
862 863 864
		if (dataOnly)
			fprintf(g_fout, "UPDATE \"pg_class\" SET \"reltriggers\" = 0 WHERE \"relname\" !~ '^pg_';\n");

865 866
		dumpClasses(tblinfo, numTables, g_fout, tablename, oids);

867 868
		if (dataOnly)
		{
869 870 871 872 873 874 875 876
			fprintf(g_fout, "BEGIN TRANSACTION;\n");
			fprintf(g_fout, "CREATE TEMP TABLE \"tr\" (\"tmp_relname\" name, \"tmp_reltriggers\" smallint);\n");
			fprintf(g_fout, "INSERT INTO \"tr\" SELECT C.\"relname\", count(T.\"oid\") FROM \"pg_class\" C, \"pg_trigger\" T WHERE C.\"oid\" = T.\"tgrelid\" AND C.\"relname\" !~ '^pg_' GROUP BY 1;\n");
			fprintf(g_fout, "UPDATE \"pg_class\" SET \"reltriggers\" = TMP.\"tmp_reltriggers\" FROM \"tr\" TMP WHERE \"pg_class\".\"relname\" = TMP.\"tmp_relname\";\n");
			fprintf(g_fout, "COMMIT TRANSACTION;\n");
		}
	}

877 878
	if (!dataOnly)				/* dump indexes and triggers at the end
								 * for performance */
V
Vadim B. Mikheev 已提交
879 880 881
	{
		dumpSchemaIdx(g_fout, tablename, tblinfo, numTables);
		dumpTriggers(g_fout, tablename, tblinfo, numTables);
882
		dumpRules(g_fout, tablename, tblinfo, numTables);
V
Vadim B. Mikheev 已提交
883
	}
884 885

	fflush(g_fout);
886 887 888
	if (g_fout != stdout)
		fclose(g_fout);

889 890 891
	clearTableInfo(tblinfo, numTables);
	PQfinish(g_conn);
	exit(0);
892 893 894
}

/*
895 896
 * getTypes:
 *	  read all base types in the system catalogs and return them in the
897 898
 * TypeInfo* structure
 *
899
 *	numTypes is set to the number of types read in
900 901
 *
 */
902
TypeInfo   *
903 904
getTypes(int *numTypes)
{
B
Bruce Momjian 已提交
905
	PGresult   *res;
906 907
	int			ntups;
	int			i;
908
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
909
	TypeInfo   *tinfo;
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925

	int			i_oid;
	int			i_typowner;
	int			i_typname;
	int			i_typlen;
	int			i_typprtlen;
	int			i_typinput;
	int			i_typoutput;
	int			i_typreceive;
	int			i_typsend;
	int			i_typelem;
	int			i_typdelim;
	int			i_typdefault;
	int			i_typrelid;
	int			i_typbyval;
	int			i_usename;
926 927 928 929 930 931 932 933 934 935 936 937

	/* find all base types */

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

B
Hi, all  
Bruce Momjian 已提交
938
	appendPQExpBuffer(query, "SELECT pg_type.oid, typowner, typname, typlen, typprtlen, "
939
		  "typinput, typoutput, typreceive, typsend, typelem, typdelim, "
940 941
		 "typdefault, typrelid, typbyval, usename from pg_type, pg_user "
					  "where typowner = usesysid");
942

B
Hi, all  
Bruce Momjian 已提交
943
	res = PQexec(g_conn, query->data);
944 945 946
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
947
		fprintf(stderr, "getTypes(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	tinfo = (TypeInfo *) malloc(ntups * sizeof(TypeInfo));

	i_oid = PQfnumber(res, "oid");
	i_typowner = PQfnumber(res, "typowner");
	i_typname = PQfnumber(res, "typname");
	i_typlen = PQfnumber(res, "typlen");
	i_typprtlen = PQfnumber(res, "typprtlen");
	i_typinput = PQfnumber(res, "typinput");
	i_typoutput = PQfnumber(res, "typoutput");
	i_typreceive = PQfnumber(res, "typreceive");
	i_typsend = PQfnumber(res, "typsend");
	i_typelem = PQfnumber(res, "typelem");
	i_typdelim = PQfnumber(res, "typdelim");
	i_typdefault = PQfnumber(res, "typdefault");
	i_typrelid = PQfnumber(res, "typrelid");
	i_typbyval = PQfnumber(res, "typbyval");
	i_usename = PQfnumber(res, "usename");

	for (i = 0; i < ntups; i++)
	{
		tinfo[i].oid = strdup(PQgetvalue(res, i, i_oid));
		tinfo[i].typowner = strdup(PQgetvalue(res, i, i_typowner));
		tinfo[i].typname = strdup(PQgetvalue(res, i, i_typname));
		tinfo[i].typlen = strdup(PQgetvalue(res, i, i_typlen));
		tinfo[i].typprtlen = strdup(PQgetvalue(res, i, i_typprtlen));
		tinfo[i].typinput = strdup(PQgetvalue(res, i, i_typinput));
		tinfo[i].typoutput = strdup(PQgetvalue(res, i, i_typoutput));
		tinfo[i].typreceive = strdup(PQgetvalue(res, i, i_typreceive));
		tinfo[i].typsend = strdup(PQgetvalue(res, i, i_typsend));
		tinfo[i].typelem = strdup(PQgetvalue(res, i, i_typelem));
		tinfo[i].typdelim = strdup(PQgetvalue(res, i, i_typdelim));
		tinfo[i].typdefault = strdup(PQgetvalue(res, i, i_typdefault));
		tinfo[i].typrelid = strdup(PQgetvalue(res, i, i_typrelid));
		tinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));

		if (strcmp(PQgetvalue(res, i, i_typbyval), "f") == 0)
			tinfo[i].passedbyvalue = 0;
		else
			tinfo[i].passedbyvalue = 1;

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

	*numTypes = ntups;

	PQclear(res);

	return tinfo;
1008 1009 1010 1011
}

/*
 * getOperators:
1012
 *	  read all operators in the system catalogs and return them in the
1013 1014
 * OprInfo* structure
 *
1015 1016
 *	numOprs is set to the number of operators read in
 *
1017 1018
 *
 */
1019
OprInfo    *
1020 1021
getOperators(int *numOprs)
{
1022
	PGresult   *res;
1023 1024
	int			ntups;
	int			i;
1025
	PQExpBuffer query = createPQExpBuffer();
1026

B
Bruce Momjian 已提交
1027
	OprInfo    *oprinfo;
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042

	int			i_oid;
	int			i_oprname;
	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_usename;
1043 1044 1045 1046 1047 1048

	/*
	 * find all operators, including builtin operators, filter out
	 * system-defined operators at dump-out time
	 */

B
Hi, all  
Bruce Momjian 已提交
1049
	appendPQExpBuffer(query, "SELECT pg_operator.oid, oprname, oprkind, oprcode, "
1050 1051 1052 1053
			   "oprleft, oprright, oprcom, oprnegate, oprrest, oprjoin, "
					  "oprcanhash, oprlsortop, oprrsortop, usename "
					  "from pg_operator, pg_user "
					  "where oprowner = usesysid");
1054

B
Hi, all  
Bruce Momjian 已提交
1055
	res = PQexec(g_conn, query->data);
1056 1057 1058
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
1059
		fprintf(stderr, "getOperators(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
		exit_nicely(g_conn);
	}

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

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

	i_oid = PQfnumber(res, "oid");
	i_oprname = PQfnumber(res, "oprname");
	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_usename = PQfnumber(res, "usename");

	for (i = 0; i < ntups; i++)
	{
		oprinfo[i].oid = strdup(PQgetvalue(res, i, i_oid));
		oprinfo[i].oprname = strdup(PQgetvalue(res, i, i_oprname));
		oprinfo[i].oprkind = strdup(PQgetvalue(res, i, i_oprkind));
		oprinfo[i].oprcode = strdup(PQgetvalue(res, i, i_oprcode));
		oprinfo[i].oprleft = strdup(PQgetvalue(res, i, i_oprleft));
		oprinfo[i].oprright = strdup(PQgetvalue(res, i, i_oprright));
		oprinfo[i].oprcom = strdup(PQgetvalue(res, i, i_oprcom));
		oprinfo[i].oprnegate = strdup(PQgetvalue(res, i, i_oprnegate));
		oprinfo[i].oprrest = strdup(PQgetvalue(res, i, i_oprrest));
		oprinfo[i].oprjoin = strdup(PQgetvalue(res, i, i_oprjoin));
		oprinfo[i].oprcanhash = strdup(PQgetvalue(res, i, i_oprcanhash));
		oprinfo[i].oprlsortop = strdup(PQgetvalue(res, i, i_oprlsortop));
		oprinfo[i].oprrsortop = strdup(PQgetvalue(res, i, i_oprrsortop));
		oprinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
	}

	PQclear(res);

	return oprinfo;
1104 1105
}

1106
void
1107
clearTypeInfo(TypeInfo *tp, int numTypes)
1108
{
1109
	int			i;
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142

	for (i = 0; i < numTypes; ++i)
	{
		if (tp[i].oid)
			free(tp[i].oid);
		if (tp[i].typowner)
			free(tp[i].typowner);
		if (tp[i].typname)
			free(tp[i].typname);
		if (tp[i].typlen)
			free(tp[i].typlen);
		if (tp[i].typprtlen)
			free(tp[i].typprtlen);
		if (tp[i].typinput)
			free(tp[i].typinput);
		if (tp[i].typoutput)
			free(tp[i].typoutput);
		if (tp[i].typreceive)
			free(tp[i].typreceive);
		if (tp[i].typsend)
			free(tp[i].typsend);
		if (tp[i].typelem)
			free(tp[i].typelem);
		if (tp[i].typdelim)
			free(tp[i].typdelim);
		if (tp[i].typdefault)
			free(tp[i].typdefault);
		if (tp[i].typrelid)
			free(tp[i].typrelid);
		if (tp[i].usename)
			free(tp[i].usename);
	}
	free(tp);
1143 1144 1145
}

void
1146
clearFuncInfo(FuncInfo *fun, int numFuncs)
1147
{
1148 1149
	int			i,
				a;
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160

	if (!fun)
		return;
	for (i = 0; i < numFuncs; ++i)
	{
		if (fun[i].oid)
			free(fun[i].oid);
		if (fun[i].proname)
			free(fun[i].proname);
		if (fun[i].usename)
			free(fun[i].usename);
1161
		for (a = 0; a < FUNC_MAX_ARGS; ++a)
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
			if (fun[i].argtypes[a])
				free(fun[i].argtypes[a]);
		if (fun[i].prorettype)
			free(fun[i].prorettype);
		if (fun[i].prosrc)
			free(fun[i].prosrc);
		if (fun[i].probin)
			free(fun[i].probin);
	}
	free(fun);
1172 1173
}

1174
static void
1175
clearTableInfo(TableInfo *tblinfo, int numTables)
1176
{
1177 1178
	int			i,
				j;
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198

	for (i = 0; i < numTables; ++i)
	{

		if (tblinfo[i].oid)
			free(tblinfo[i].oid);
		if (tblinfo[i].relacl)
			free(tblinfo[i].relacl);
		if (tblinfo[i].usename)
			free(tblinfo[i].usename);

		if (tblinfo[i].relname)
			free(tblinfo[i].relname);

		if (tblinfo[i].sequence)
			continue;

		/* Process Attributes */
		for (j = 0; j < tblinfo[i].numatts; j++)
		{
B
Bruce,  
Bruce Momjian 已提交
1199 1200
			if (tblinfo[i].attoids[j])
				free(tblinfo[i].attoids[j]);
1201 1202 1203 1204 1205
			if (tblinfo[i].attnames[j])
				free(tblinfo[i].attnames[j]);
			if (tblinfo[i].typnames[j])
				free(tblinfo[i].typnames[j]);
		}
1206 1207
		if (tblinfo[i].atttypmod)
			free((int *) tblinfo[i].atttypmod);
1208 1209 1210 1211 1212 1213 1214 1215
		if (tblinfo[i].inhAttrs)
			free((int *) tblinfo[i].inhAttrs);
		if (tblinfo[i].attnames)
			free(tblinfo[i].attnames);
		if (tblinfo[i].typnames)
			free(tblinfo[i].typnames);
		if (tblinfo[i].notnull)
			free(tblinfo[i].notnull);
1216 1217
		if (tblinfo[i].primary_key)
			free(tblinfo[i].primary_key);
1218 1219
	}
	free(tblinfo);
1220 1221
}

1222
void
1223
clearInhInfo(InhInfo *inh, int numInherits)
1224
{
1225
	int			i;
1226 1227 1228 1229 1230

	if (!inh)
		return;
	for (i = 0; i < numInherits; ++i)
	{
1231 1232
		if (inh[i].inhrelid)
			free(inh[i].inhrelid);
1233 1234 1235 1236
		if (inh[i].inhparent)
			free(inh[i].inhparent);
	}
	free(inh);
1237 1238 1239
}

void
1240
clearOprInfo(OprInfo *opr, int numOprs)
1241
{
1242
	int			i;
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277

	if (!opr)
		return;
	for (i = 0; i < numOprs; ++i)
	{
		if (opr[i].oid)
			free(opr[i].oid);
		if (opr[i].oprname)
			free(opr[i].oprname);
		if (opr[i].oprkind)
			free(opr[i].oprkind);
		if (opr[i].oprcode)
			free(opr[i].oprcode);
		if (opr[i].oprleft)
			free(opr[i].oprleft);
		if (opr[i].oprright)
			free(opr[i].oprright);
		if (opr[i].oprcom)
			free(opr[i].oprcom);
		if (opr[i].oprnegate)
			free(opr[i].oprnegate);
		if (opr[i].oprrest)
			free(opr[i].oprrest);
		if (opr[i].oprjoin)
			free(opr[i].oprjoin);
		if (opr[i].oprcanhash)
			free(opr[i].oprcanhash);
		if (opr[i].oprlsortop)
			free(opr[i].oprlsortop);
		if (opr[i].oprrsortop)
			free(opr[i].oprrsortop);
		if (opr[i].usename)
			free(opr[i].usename);
	}
	free(opr);
1278 1279 1280
}

void
1281
clearIndInfo(IndInfo *ind, int numIndices)
1282
{
1283 1284
	int			i,
				a;
1285 1286 1287 1288 1289

	if (!ind)
		return;
	for (i = 0; i < numIndices; ++i)
	{
B
Bruce,  
Bruce Momjian 已提交
1290 1291
		if (ind[i].indoid)
			free(ind[i].indoid);
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
		if (ind[i].indexrelname)
			free(ind[i].indexrelname);
		if (ind[i].indrelname)
			free(ind[i].indrelname);
		if (ind[i].indamname)
			free(ind[i].indamname);
		if (ind[i].indproc)
			free(ind[i].indproc);
		if (ind[i].indisunique)
			free(ind[i].indisunique);
		for (a = 0; a < INDEX_MAX_KEYS; ++a)
		{
			if (ind[i].indkey[a])
				free(ind[i].indkey[a]);
			if (ind[i].indclass[a])
				free(ind[i].indclass[a]);
		}
	}
	free(ind);
1311 1312 1313
}

void
B
Bruce Momjian 已提交
1314
clearAggInfo(AggInfo *agginfo, int numArgs)
1315
{
1316
	int			i;
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345

	if (!agginfo)
		return;
	for (i = 0; i < numArgs; ++i)
	{
		if (agginfo[i].oid)
			free(agginfo[i].oid);
		if (agginfo[i].aggname)
			free(agginfo[i].aggname);
		if (agginfo[i].aggtransfn1)
			free(agginfo[i].aggtransfn1);
		if (agginfo[i].aggtransfn2)
			free(agginfo[i].aggtransfn2);
		if (agginfo[i].aggfinalfn)
			free(agginfo[i].aggfinalfn);
		if (agginfo[i].aggtranstype1)
			free(agginfo[i].aggtranstype1);
		if (agginfo[i].aggbasetype)
			free(agginfo[i].aggbasetype);
		if (agginfo[i].aggtranstype2)
			free(agginfo[i].aggtranstype2);
		if (agginfo[i].agginitval1)
			free(agginfo[i].agginitval1);
		if (agginfo[i].agginitval2)
			free(agginfo[i].agginitval2);
		if (agginfo[i].usename)
			free(agginfo[i].usename);
	}
	free(agginfo);
1346
}
1347 1348 1349

/*
 * getAggregates:
1350
 *	  read all the user-defined aggregates in the system catalogs and
1351 1352
 * return them in the AggInfo* structure
 *
1353 1354
 * numAggs is set to the number of aggregates read in
 *
1355 1356
 *
 */
1357
AggInfo    *
1358 1359
getAggregates(int *numAggs)
{
B
Bruce Momjian 已提交
1360
	PGresult   *res;
1361 1362
	int			ntups;
	int			i;
1363
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
1364
	AggInfo    *agginfo;
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376

	int			i_oid;
	int			i_aggname;
	int			i_aggtransfn1;
	int			i_aggtransfn2;
	int			i_aggfinalfn;
	int			i_aggtranstype1;
	int			i_aggbasetype;
	int			i_aggtranstype2;
	int			i_agginitval1;
	int			i_agginitval2;
	int			i_usename;
1377 1378 1379

	/* find all user-defined aggregates */

B
Hi, all  
Bruce Momjian 已提交
1380
	appendPQExpBuffer(query,
1381 1382
		   "SELECT pg_aggregate.oid, aggname, aggtransfn1, aggtransfn2, "
				"aggfinalfn, aggtranstype1, aggbasetype, aggtranstype2, "
1383
		  "agginitval1, agginitval2, usename from pg_aggregate, pg_user "
1384
					  "where aggowner = usesysid");
1385

B
Hi, all  
Bruce Momjian 已提交
1386
	res = PQexec(g_conn, query->data);
1387 1388 1389
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
1390
		fprintf(stderr, "getAggregates(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
		exit_nicely(g_conn);
	}

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

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

	i_oid = PQfnumber(res, "oid");
	i_aggname = PQfnumber(res, "aggname");
	i_aggtransfn1 = PQfnumber(res, "aggtransfn1");
	i_aggtransfn2 = PQfnumber(res, "aggtransfn2");
	i_aggfinalfn = PQfnumber(res, "aggfinalfn");
	i_aggtranstype1 = PQfnumber(res, "aggtranstype1");
	i_aggbasetype = PQfnumber(res, "aggbasetype");
	i_aggtranstype2 = PQfnumber(res, "aggtranstype2");
	i_agginitval1 = PQfnumber(res, "agginitval1");
	i_agginitval2 = PQfnumber(res, "agginitval2");
	i_usename = PQfnumber(res, "usename");

	for (i = 0; i < ntups; i++)
	{
		agginfo[i].oid = strdup(PQgetvalue(res, i, i_oid));
		agginfo[i].aggname = strdup(PQgetvalue(res, i, i_aggname));
		agginfo[i].aggtransfn1 = strdup(PQgetvalue(res, i, i_aggtransfn1));
		agginfo[i].aggtransfn2 = strdup(PQgetvalue(res, i, i_aggtransfn2));
		agginfo[i].aggfinalfn = strdup(PQgetvalue(res, i, i_aggfinalfn));
		agginfo[i].aggtranstype1 = strdup(PQgetvalue(res, i, i_aggtranstype1));
		agginfo[i].aggbasetype = strdup(PQgetvalue(res, i, i_aggbasetype));
		agginfo[i].aggtranstype2 = strdup(PQgetvalue(res, i, i_aggtranstype2));
		agginfo[i].agginitval1 = strdup(PQgetvalue(res, i, i_agginitval1));
		agginfo[i].agginitval2 = strdup(PQgetvalue(res, i, i_agginitval2));
		agginfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
	}

	PQclear(res);

	return agginfo;
1429 1430 1431 1432
}

/*
 * getFuncs:
1433
 *	  read all the user-defined functions in the system catalogs and
1434 1435
 * return them in the FuncInfo* structure
 *
1436 1437
 * numFuncs is set to the number of functions read in
 *
1438 1439
 *
 */
1440
FuncInfo   *
1441 1442
getFuncs(int *numFuncs)
{
1443
	PGresult   *res;
1444 1445
	int			ntups;
	int			i;
1446 1447
	PQExpBuffer query = createPQExpBuffer();
	FuncInfo   *finfo;
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458

	int			i_oid;
	int			i_proname;
	int			i_prolang;
	int			i_pronargs;
	int			i_proargtypes;
	int			i_prorettype;
	int			i_proretset;
	int			i_prosrc;
	int			i_probin;
	int			i_usename;
1459 1460 1461

	/* find all user-defined funcs */

B
Hi, all  
Bruce Momjian 已提交
1462
	appendPQExpBuffer(query,
1463 1464 1465 1466 1467
		   "SELECT pg_proc.oid, proname, prolang, pronargs, prorettype, "
					  "proretset, proargtypes, prosrc, probin, usename "
					  "from pg_proc, pg_user "
				 "where pg_proc.oid > '%u'::oid and proowner = usesysid",
					  g_last_builtin_oid);
1468

B
Hi, all  
Bruce Momjian 已提交
1469
	res = PQexec(g_conn, query->data);
1470 1471 1472
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
1473
		fprintf(stderr, "getFuncs(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1474 1475 1476 1477 1478 1479 1480 1481 1482
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numFuncs = ntups;

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

1483 1484
	memset((char *) finfo, 0, ntups * sizeof(FuncInfo));

1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
	i_oid = PQfnumber(res, "oid");
	i_proname = PQfnumber(res, "proname");
	i_prolang = PQfnumber(res, "prolang");
	i_pronargs = PQfnumber(res, "pronargs");
	i_proargtypes = PQfnumber(res, "proargtypes");
	i_prorettype = PQfnumber(res, "prorettype");
	i_proretset = PQfnumber(res, "proretset");
	i_prosrc = PQfnumber(res, "prosrc");
	i_probin = PQfnumber(res, "probin");
	i_usename = PQfnumber(res, "usename");

	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].prosrc = checkForQuote(PQgetvalue(res, i, i_prosrc));
		finfo[i].probin = strdup(PQgetvalue(res, i, i_probin));

		finfo[i].prorettype = strdup(PQgetvalue(res, i, i_prorettype));
		finfo[i].retset = (strcmp(PQgetvalue(res, i, i_proretset), "t") == 0);
		finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
1507
		finfo[i].lang = atoi(PQgetvalue(res, i, i_prolang));
1508
		finfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1509 1510 1511 1512
		if (finfo[i].nargs < 0 || finfo[i].nargs > FUNC_MAX_ARGS)
		{
			fprintf(stderr, "failed sanity check: %s has %d args\n",
					finfo[i].proname, finfo[i].nargs);
1513
			exit(1);
1514 1515 1516 1517
		}
		parseNumericArray(PQgetvalue(res, i, i_proargtypes),
						  finfo[i].argtypes,
						  finfo[i].nargs);
1518 1519 1520 1521 1522 1523
		finfo[i].dumped = 0;
	}

	PQclear(res);

	return finfo;
1524 1525 1526 1527 1528

}

/*
 * getTables
1529
 *	  read all the user-defined tables (no indices, no catalogs)
1530 1531
 * in the system catalogs return them in the TableInfo* structure
 *
1532 1533
 * numTables is set to the number of tables read in
 *
1534 1535
 *
 */
1536
TableInfo  *
V
Vadim B. Mikheev 已提交
1537
getTables(int *numTables, FuncInfo *finfo, int numFuncs)
1538
{
1539
	PGresult   *res;
1540 1541
	int			ntups;
	int			i;
1542 1543
	PQExpBuffer query = createPQExpBuffer();
	TableInfo  *tblinfo;
1544 1545 1546 1547 1548 1549

	int			i_oid;
	int			i_relname;
	int			i_relkind;
	int			i_relacl;
	int			i_usename;
V
Vadim B. Mikheev 已提交
1550 1551
	int			i_relchecks;
	int			i_reltriggers;
1552
	int			i_relhasindex;
1553 1554 1555 1556 1557 1558

	/*
	 * find all the user-defined tables (no indices and no catalogs),
	 * ordering by oid is important so that we always process the parent
	 * tables before the child tables when traversing the tblinfo*
	 *
1559 1560 1561
	 * we ignore tables that are not type 'r' (ordinary relation) or 'S'
	 * (sequence) --- in particular, Large Object relations (type 'l') are
	 * ignored.
1562 1563
	 */

B
Hi, all  
Bruce Momjian 已提交
1564
	appendPQExpBuffer(query,
1565 1566 1567 1568 1569 1570
			   "SELECT pg_class.oid, relname, relkind, relacl, usename, "
					  "relchecks, reltriggers, relhasindex "
					  "from pg_class, pg_user "
					  "where relowner = usesysid and "
				"(relkind = 'r' or relkind = 'S') and relname !~ '^pg_' "
					  "order by oid");
1571

B
Hi, all  
Bruce Momjian 已提交
1572
	res = PQexec(g_conn, query->data);
1573 1574 1575
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
1576
		fprintf(stderr, "getTables(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numTables = ntups;

	tblinfo = (TableInfo *) malloc(ntups * sizeof(TableInfo));

	i_oid = PQfnumber(res, "oid");
	i_relname = PQfnumber(res, "relname");
	i_relkind = PQfnumber(res, "relkind");
	i_relacl = PQfnumber(res, "relacl");
	i_usename = PQfnumber(res, "usename");
V
Vadim B. Mikheev 已提交
1591 1592
	i_relchecks = PQfnumber(res, "relchecks");
	i_reltriggers = PQfnumber(res, "reltriggers");
B
Hi, all  
Bruce Momjian 已提交
1593
	i_relhasindex = PQfnumber(res, "relhasindex");
1594 1595 1596 1597 1598 1599 1600 1601

	for (i = 0; i < ntups; i++)
	{
		tblinfo[i].oid = strdup(PQgetvalue(res, i, i_oid));
		tblinfo[i].relname = strdup(PQgetvalue(res, i, i_relname));
		tblinfo[i].relacl = strdup(PQgetvalue(res, i, i_relacl));
		tblinfo[i].sequence = (strcmp(PQgetvalue(res, i, i_relkind), "S") == 0);
		tblinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
V
Vadim B. Mikheev 已提交
1602 1603
		tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
		tblinfo[i].ntrig = atoi(PQgetvalue(res, i, i_reltriggers));
1604

B
Bruce Momjian 已提交
1605 1606 1607
		/*
		 * Exclude inherited CHECKs from CHECK constraints total. If a
		 * constraint matches by name and condition with a constraint
1608 1609 1610 1611
		 * belonging to a parent class, we assume it was inherited.
		 */
		if (tblinfo[i].ncheck > 0)
		{
B
Bruce Momjian 已提交
1612
			PGresult   *res2;
1613 1614
			int			ntups2;

B
Bruce Momjian 已提交
1615
			if (g_verbose)
1616 1617 1618 1619 1620 1621
				fprintf(stderr, "%s excluding inherited CHECK constraints "
						"for relation: '%s' %s\n",
						g_comment_start,
						tblinfo[i].relname,
						g_comment_end);

B
Hi, all  
Bruce Momjian 已提交
1622 1623
			resetPQExpBuffer(query);
			appendPQExpBuffer(query, "SELECT rcname from pg_relcheck, pg_inherits as i "
1624 1625 1626 1627 1628 1629 1630 1631
							  "where rcrelid = '%s'::oid "
							  " and rcrelid = i.inhrelid"
							  " and exists "
							  "  (select * from pg_relcheck as c "
							  "    where c.rcname = pg_relcheck.rcname "
							  "      and c.rcsrc = pg_relcheck.rcsrc "
							  "      and c.rcrelid = i.inhparent) ",
							  tblinfo[i].oid);
B
Hi, all  
Bruce Momjian 已提交
1632
			res2 = PQexec(g_conn, query->data);
1633 1634 1635
			if (!res2 ||
				PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
B
Bruce Momjian 已提交
1636
				fprintf(stderr, "getTables(): SELECT (for inherited CHECK) failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
				exit_nicely(g_conn);
			}
			ntups2 = PQntuples(res2);
			tblinfo[i].ncheck -= ntups2;
			if (tblinfo[i].ncheck < 0)
			{
				fprintf(stderr, "getTables(): found more inherited CHECKs than total for "
						"relation %s\n",
						tblinfo[i].relname);
				exit_nicely(g_conn);
			}
			PQclear(res2);
		}

		/* Get non-inherited CHECK constraints, if any */
V
Vadim B. Mikheev 已提交
1652 1653 1654
		if (tblinfo[i].ncheck > 0)
		{
			PGresult   *res2;
1655 1656
			int			i_rcname,
						i_rcsrc;
V
Vadim B. Mikheev 已提交
1657 1658
			int			ntups2;
			int			i2;
1659

V
Vadim B. Mikheev 已提交
1660
			if (g_verbose)
1661
				fprintf(stderr, "%s finding CHECK constraints for relation: '%s' %s\n",
V
Vadim B. Mikheev 已提交
1662 1663 1664
						g_comment_start,
						tblinfo[i].relname,
						g_comment_end);
1665

B
Hi, all  
Bruce Momjian 已提交
1666 1667
			resetPQExpBuffer(query);
			appendPQExpBuffer(query, "SELECT rcname, rcsrc from pg_relcheck "
1668 1669 1670 1671 1672 1673 1674 1675
							  "where rcrelid = '%s'::oid "
							  "   and not exists "
				   "  (select * from pg_relcheck as c, pg_inherits as i "
							  "   where i.inhrelid = pg_relcheck.rcrelid "
							  "     and c.rcname = pg_relcheck.rcname "
							  "     and c.rcsrc = pg_relcheck.rcsrc "
							  "     and c.rcrelid = i.inhparent) ",
							  tblinfo[i].oid);
B
Hi, all  
Bruce Momjian 已提交
1676
			res2 = PQexec(g_conn, query->data);
V
Vadim B. Mikheev 已提交
1677
			if (!res2 ||
1678
				PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
1679
			{
B
Bruce Momjian 已提交
1680
				fprintf(stderr, "getTables(): SELECT (for CHECK) failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
V
Vadim B. Mikheev 已提交
1681 1682 1683 1684 1685
				exit_nicely(g_conn);
			}
			ntups2 = PQntuples(res2);
			if (ntups2 != tblinfo[i].ncheck)
			{
1686
				fprintf(stderr, "getTables(): relation '%s': %d CHECKs were expected, but got %d\n",
1687
						tblinfo[i].relname, tblinfo[i].ncheck, ntups2);
V
Vadim B. Mikheev 已提交
1688 1689 1690 1691
				exit_nicely(g_conn);
			}
			i_rcname = PQfnumber(res2, "rcname");
			i_rcsrc = PQfnumber(res2, "rcsrc");
1692
			tblinfo[i].check_expr = (char **) malloc(ntups2 * sizeof(char *));
V
Vadim B. Mikheev 已提交
1693 1694
			for (i2 = 0; i2 < ntups2; i2++)
			{
B
Bruce Momjian 已提交
1695 1696
				const char *name = PQgetvalue(res2, i2, i_rcname);
				const char *expr = PQgetvalue(res2, i2, i_rcsrc);
1697

B
Hi, all  
Bruce Momjian 已提交
1698
				resetPQExpBuffer(query);
1699 1700
				if (name[0] != '$')
				{
1701 1702
					appendPQExpBuffer(query, "CONSTRAINT %s ",
									  fmtId(name, force_quotes));
B
Bruce Momjian 已提交
1703
				}
1704
				appendPQExpBuffer(query, "CHECK (%s)", expr);
B
Hi, all  
Bruce Momjian 已提交
1705
				tblinfo[i].check_expr[i2] = strdup(query->data);
V
Vadim B. Mikheev 已提交
1706 1707 1708 1709 1710
			}
			PQclear(res2);
		}
		else
			tblinfo[i].check_expr = NULL;
1711

1712 1713
		/* Get primary key */
		if (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0)
1714
		{
1715 1716 1717
			PGresult   *res2;
			char		str[INDEX_MAX_KEYS * (NAMEDATALEN * 2 + 4) + 1];
			int			j;
B
Bruce Momjian 已提交
1718

B
Hi, all  
Bruce Momjian 已提交
1719
			resetPQExpBuffer(query);
B
Bruce Momjian 已提交
1720
			appendPQExpBuffer(query,
1721 1722 1723 1724 1725 1726
							  "SELECT a.attname "
						   "FROM pg_index i, pg_class c, pg_attribute a "
							  "WHERE i.indisprimary AND i.indrelid = %s "
							  "  AND i.indexrelid = c.oid AND a.attnum > 0 AND a.attrelid = c.oid "
							  "ORDER BY a.attnum ",
							  tblinfo[i].oid);
1727
			res2 = PQexec(g_conn, query->data);
B
Bruce Momjian 已提交
1728 1729 1730
			if (!res2 || PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
				fprintf(stderr, "getTables(): SELECT (for PRIMARY KEY) failed.  Explanation from backend: %s",
1731
						PQerrorMessage(g_conn));
B
Bruce Momjian 已提交
1732 1733
				exit_nicely(g_conn);
			}
1734

1735 1736 1737
			str[0] = '\0';
			for (j = 0; j < PQntuples(res2); j++)
			{
1738
				if (strlen(str) > 0)
1739 1740 1741 1742
					strcat(str, ", ");
				strcat(str, fmtId(PQgetvalue(res2, j, 0), force_quotes));
			}

1743 1744
			if (strlen(str) > 0)
			{
1745
				tblinfo[i].primary_key = strdup(str);
1746 1747
				if (tblinfo[i].primary_key == NULL)
				{
1748 1749 1750 1751 1752 1753
					perror("strdup");
					exit(1);
				}
			}
			else
				tblinfo[i].primary_key = NULL;
1754
		}
1755 1756
		else
			tblinfo[i].primary_key = NULL;
B
Bruce Momjian 已提交
1757

V
Vadim B. Mikheev 已提交
1758 1759 1760 1761
		/* Get Triggers */
		if (tblinfo[i].ntrig > 0)
		{
			PGresult   *res2;
B
Bruce,  
Bruce Momjian 已提交
1762
			int			i_tgoid,
1763
						i_tgname,
1764 1765 1766
						i_tgfoid,
						i_tgtype,
						i_tgnargs,
1767 1768 1769 1770 1771
						i_tgargs,
						i_tgisconstraint,
						i_tgconstrname,
						i_tgdeferrable,
						i_tginitdeferred;
V
Vadim B. Mikheev 已提交
1772 1773
			int			ntups2;
			int			i2;
1774

V
Vadim B. Mikheev 已提交
1775
			if (g_verbose)
1776
				fprintf(stderr, "%s finding Triggers for relation: '%s' %s\n",
V
Vadim B. Mikheev 已提交
1777 1778 1779
						g_comment_start,
						tblinfo[i].relname,
						g_comment_end);
1780

B
Hi, all  
Bruce Momjian 已提交
1781
			resetPQExpBuffer(query);
1782
			appendPQExpBuffer(query, "SELECT tgname, tgfoid, tgtype, tgnargs, tgargs, tgisconstraint, tgconstrname, tgdeferrable, tginitdeferred, oid "
1783 1784 1785
							  "from pg_trigger "
							  "where tgrelid = '%s'::oid ",
							  tblinfo[i].oid);
B
Hi, all  
Bruce Momjian 已提交
1786
			res2 = PQexec(g_conn, query->data);
V
Vadim B. Mikheev 已提交
1787
			if (!res2 ||
1788
				PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
1789
			{
B
Bruce Momjian 已提交
1790
				fprintf(stderr, "getTables(): SELECT (for TRIGGER) failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
V
Vadim B. Mikheev 已提交
1791 1792 1793 1794 1795
				exit_nicely(g_conn);
			}
			ntups2 = PQntuples(res2);
			if (ntups2 != tblinfo[i].ntrig)
			{
1796
				fprintf(stderr, "getTables(): relation '%s': %d Triggers were expected, but got %d\n",
1797
						tblinfo[i].relname, tblinfo[i].ntrig, ntups2);
V
Vadim B. Mikheev 已提交
1798 1799 1800 1801 1802 1803 1804
				exit_nicely(g_conn);
			}
			i_tgname = PQfnumber(res2, "tgname");
			i_tgfoid = PQfnumber(res2, "tgfoid");
			i_tgtype = PQfnumber(res2, "tgtype");
			i_tgnargs = PQfnumber(res2, "tgnargs");
			i_tgargs = PQfnumber(res2, "tgargs");
B
Bruce,  
Bruce Momjian 已提交
1805
			i_tgoid = PQfnumber(res2, "oid");
1806 1807 1808 1809 1810
			i_tgisconstraint = PQfnumber(res2, "tgisconstraint");
			i_tgconstrname = PQfnumber(res2, "tgconstrname");
			i_tgdeferrable = PQfnumber(res2, "tgdeferrable");
			i_tginitdeferred = PQfnumber(res2, "tginitdeferred");

1811
			tblinfo[i].triggers = (char **) malloc(ntups2 * sizeof(char *));
B
Bruce,  
Bruce Momjian 已提交
1812 1813
			tblinfo[i].trcomments = (char **) malloc(ntups2 * sizeof(char *));
			tblinfo[i].troids = (char **) malloc(ntups2 * sizeof(char *));
B
Hi, all  
Bruce Momjian 已提交
1814 1815
			resetPQExpBuffer(query);
			for (i2 = 0; i2 < ntups2; i2++)
V
Vadim B. Mikheev 已提交
1816
			{
1817
				const char *tgfuncoid = PQgetvalue(res2, i2, i_tgfoid);
1818
				char	   *tgfunc = NULL;
1819 1820
				int2		tgtype = atoi(PQgetvalue(res2, i2, i_tgtype));
				int			tgnargs = atoi(PQgetvalue(res2, i2, i_tgnargs));
B
Bruce Momjian 已提交
1821
				const char *tgargs = PQgetvalue(res2, i2, i_tgargs);
1822 1823 1824
				int			tgisconstraint;
				int			tgdeferrable;
				int			tginitdeferred;
B
Bruce Momjian 已提交
1825
				const char *p;
1826 1827
				int			findx;

1828
				if (strcmp(PQgetvalue(res2, i2, i_tgisconstraint), "f") == 0)
1829
					tgisconstraint = 0;
1830
				else
1831
					tgisconstraint = 1;
1832 1833

				if (strcmp(PQgetvalue(res2, i2, i_tgdeferrable), "f") == 0)
1834
					tgdeferrable = 0;
1835
				else
1836
					tgdeferrable = 1;
1837 1838

				if (strcmp(PQgetvalue(res2, i2, i_tginitdeferred), "f") == 0)
1839
					tginitdeferred = 0;
1840
				else
1841
					tginitdeferred = 1;
1842

V
Vadim B. Mikheev 已提交
1843 1844
				for (findx = 0; findx < numFuncs; findx++)
				{
1845
					if (strcmp(finfo[findx].oid, tgfuncoid) == 0 &&
1846
						finfo[findx].nargs == 0 &&
V
Vadim B. Mikheev 已提交
1847 1848 1849
						strcmp(finfo[findx].prorettype, "0") == 0)
						break;
				}
1850

V
Vadim B. Mikheev 已提交
1851 1852
				if (findx == numFuncs)
				{
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
					PGresult   *r;

					/*
					 * the funcname is an oid which we use to find the
					 * name of the pg_proc.  We need to do this because
					 * getFuncs() only reads in the user-defined funcs not
					 * all the funcs.  We might not find what we want by
					 * looking in FuncInfo*
					 */
					resetPQExpBuffer(query);
					appendPQExpBuffer(query,
									  "SELECT proname from pg_proc "
									  "where pg_proc.oid = '%s'::oid",
									  tgfuncoid);

					r = PQexec(g_conn, query->data);
					if (!r || PQresultStatus(r) != PGRES_TUPLES_OK)
					{
						fprintf(stderr, "getTables(): SELECT (funcname) failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
						exit_nicely(g_conn);
					}
1874
					tgfunc = strdup(PQgetvalue(r, 0, PQfnumber(r, "proname")));
1875
					PQclear(r);
1876
				}
1877
				else
1878
					tgfunc = strdup(finfo[findx].proname);
B
Bruce Momjian 已提交
1879
#if 0
1880
				/* XXX - how to emit this DROP TRIGGER? */
1881
				if (dropSchema)
B
Bruce Momjian 已提交
1882
				{
B
Hi, all  
Bruce Momjian 已提交
1883
					resetPQExpBuffer(query);
1884
					appendPQExpBuffer(query, "DROP TRIGGER %s ",
1885 1886
									fmtId(PQgetvalue(res2, i2, i_tgname),
										  force_quotes));
1887
					appendPQExpBuffer(query, "ON %s;\n",
1888
								fmtId(tblinfo[i].relname, force_quotes));
B
Hi, all  
Bruce Momjian 已提交
1889
					fputs(query->data, fout);
B
Bruce Momjian 已提交
1890
				}
1891 1892
#endif

B
Hi, all  
Bruce Momjian 已提交
1893
				resetPQExpBuffer(query);
1894 1895 1896 1897 1898
				if (tgisconstraint)
				{
					appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
					appendPQExpBuffer(query, fmtId(PQgetvalue(res2, i2, i_tgconstrname), force_quotes));
				}
1899 1900
				else
				{
1901 1902 1903
					appendPQExpBuffer(query, "CREATE TRIGGER ");
					appendPQExpBuffer(query, fmtId(PQgetvalue(res2, i2, i_tgname), force_quotes));
				}
B
Bruce Momjian 已提交
1904
				appendPQExpBufferChar(query, ' ');
V
Vadim B. Mikheev 已提交
1905 1906 1907
				/* Trigger type */
				findx = 0;
				if (TRIGGER_FOR_BEFORE(tgtype))
B
Hi, all  
Bruce Momjian 已提交
1908
					appendPQExpBuffer(query, "BEFORE");
V
Vadim B. Mikheev 已提交
1909
				else
B
Hi, all  
Bruce Momjian 已提交
1910
					appendPQExpBuffer(query, "AFTER");
V
Vadim B. Mikheev 已提交
1911 1912
				if (TRIGGER_FOR_INSERT(tgtype))
				{
B
Hi, all  
Bruce Momjian 已提交
1913
					appendPQExpBuffer(query, " INSERT");
V
Vadim B. Mikheev 已提交
1914 1915 1916 1917 1918
					findx++;
				}
				if (TRIGGER_FOR_DELETE(tgtype))
				{
					if (findx > 0)
B
Hi, all  
Bruce Momjian 已提交
1919
						appendPQExpBuffer(query, " OR DELETE");
V
Vadim B. Mikheev 已提交
1920
					else
B
Hi, all  
Bruce Momjian 已提交
1921
						appendPQExpBuffer(query, " DELETE");
V
Vadim B. Mikheev 已提交
1922 1923 1924
					findx++;
				}
				if (TRIGGER_FOR_UPDATE(tgtype))
1925
				{
V
Vadim B. Mikheev 已提交
1926
					if (findx > 0)
B
Hi, all  
Bruce Momjian 已提交
1927
						appendPQExpBuffer(query, " OR UPDATE");
V
Vadim B. Mikheev 已提交
1928
					else
B
Hi, all  
Bruce Momjian 已提交
1929
						appendPQExpBuffer(query, " UPDATE");
1930
				}
1931 1932
				appendPQExpBuffer(query, " ON %s ", fmtId(tblinfo[i].relname, force_quotes));

1933
				if (tgisconstraint)
1934
				{
1935
					if (!tgdeferrable)
1936 1937 1938 1939
						appendPQExpBuffer(query, " NOT");
					appendPQExpBuffer(query, " DEFERRABLE INITIALLY ");
					if (tginitdeferred)
						appendPQExpBuffer(query, "DEFERRED");
1940
					else
1941
						appendPQExpBuffer(query, "IMMEDIATE");
1942

1943 1944 1945
				}

				appendPQExpBuffer(query, " FOR EACH ROW");
1946 1947
				appendPQExpBuffer(query, " EXECUTE PROCEDURE %s (",
								  fmtId(tgfunc, force_quotes));
V
Vadim B. Mikheev 已提交
1948 1949
				for (findx = 0; findx < tgnargs; findx++)
				{
1950
					const char *s;
1951 1952

					for (p = tgargs;;)
V
Vadim B. Mikheev 已提交
1953
					{
1954
						p = strchr(p, '\\');
V
Vadim B. Mikheev 已提交
1955 1956
						if (p == NULL)
						{
1957
							fprintf(stderr, "getTables(): relation '%s': bad argument string (%s) for trigger '%s'\n",
1958 1959 1960
									tblinfo[i].relname,
									PQgetvalue(res2, i2, i_tgargs),
									PQgetvalue(res2, i2, i_tgname));
V
Vadim B. Mikheev 已提交
1961 1962 1963 1964 1965 1966 1967 1968
							exit_nicely(g_conn);
						}
						p++;
						if (*p == '\\')
						{
							p++;
							continue;
						}
1969
						if (p[0] == '0' && p[1] == '0' && p[2] == '0')
V
Vadim B. Mikheev 已提交
1970 1971 1972
							break;
					}
					p--;
1973
					appendPQExpBufferChar(query, '\'');
B
Bruce Momjian 已提交
1974
					for (s = tgargs; s < p;)
V
Vadim B. Mikheev 已提交
1975 1976
					{
						if (*s == '\'')
1977 1978
							appendPQExpBufferChar(query, '\\');
						appendPQExpBufferChar(query, *s++);
V
Vadim B. Mikheev 已提交
1979
					}
B
Bruce Momjian 已提交
1980 1981
					appendPQExpBufferChar(query, '\'');
					appendPQExpBuffer(query, (findx < tgnargs - 1) ? ", " : "");
V
Vadim B. Mikheev 已提交
1982 1983
					tgargs = p + 4;
				}
B
Hi, all  
Bruce Momjian 已提交
1984
				appendPQExpBuffer(query, ");\n");
1985

B
Hi, all  
Bruce Momjian 已提交
1986
				tblinfo[i].triggers[i2] = strdup(query->data);
B
Bruce,  
Bruce Momjian 已提交
1987 1988

				/*** Initialize trcomments and troids ***/
1989

B
Bruce,  
Bruce Momjian 已提交
1990
				resetPQExpBuffer(query);
1991 1992
				appendPQExpBuffer(query, "TRIGGER %s ",
					fmtId(PQgetvalue(res2, i2, i_tgname), force_quotes));
B
Bruce,  
Bruce Momjian 已提交
1993
				appendPQExpBuffer(query, "ON %s",
1994
								fmtId(tblinfo[i].relname, force_quotes));
B
Bruce,  
Bruce Momjian 已提交
1995 1996 1997
				tblinfo[i].trcomments[i2] = strdup(query->data);
				tblinfo[i].troids[i2] = strdup(PQgetvalue(res2, i2, i_tgoid));

1998 1999
				if (tgfunc)
					free(tgfunc);
V
Vadim B. Mikheev 已提交
2000 2001 2002 2003
			}
			PQclear(res2);
		}
		else
B
Bruce,  
Bruce Momjian 已提交
2004
		{
V
Vadim B. Mikheev 已提交
2005
			tblinfo[i].triggers = NULL;
B
Bruce,  
Bruce Momjian 已提交
2006 2007 2008
			tblinfo[i].trcomments = NULL;
			tblinfo[i].troids = NULL;
		}
2009

2010 2011 2012 2013 2014
	}

	PQclear(res);

	return tblinfo;
2015 2016 2017 2018 2019

}

/*
 * getInherits
2020
 *	  read all the inheritance information
2021 2022
 * from the system catalogs return them in the InhInfo* structure
 *
2023 2024
 * numInherits is set to the number of tables read in
 *
2025 2026
 *
 */
2027
InhInfo    *
2028 2029
getInherits(int *numInherits)
{
2030
	PGresult   *res;
2031 2032
	int			ntups;
	int			i;
2033 2034
	PQExpBuffer query = createPQExpBuffer();
	InhInfo    *inhinfo;
2035

2036
	int			i_inhrelid;
2037
	int			i_inhparent;
2038 2039 2040

	/* find all the inheritance information */

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

B
Hi, all  
Bruce Momjian 已提交
2043
	res = PQexec(g_conn, query->data);
2044 2045 2046
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
2047
		fprintf(stderr, "getInherits(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
2048 2049 2050 2051 2052 2053 2054 2055 2056
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numInherits = ntups;

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

2057
	i_inhrelid = PQfnumber(res, "inhrelid");
2058 2059 2060 2061
	i_inhparent = PQfnumber(res, "inhparent");

	for (i = 0; i < ntups; i++)
	{
2062
		inhinfo[i].inhrelid = strdup(PQgetvalue(res, i, i_inhrelid));
2063 2064 2065 2066 2067
		inhinfo[i].inhparent = strdup(PQgetvalue(res, i, i_inhparent));
	}

	PQclear(res);
	return inhinfo;
2068 2069 2070 2071
}

/*
 * getTableAttrs -
2072 2073
 *	  for each table in tblinfo, read its attributes types and names
 *
2074
 * this is implemented in a very inefficient way right now, looping
2075
 * through the tblinfo and doing a join per table to find the attrs and their
2076 2077
 * types
 *
2078
 *	modifies tblinfo
2079 2080
 */
void
2081
getTableAttrs(TableInfo *tblinfo, int numTables)
2082
{
2083 2084
	int			i,
				j;
2085
	PQExpBuffer q = createPQExpBuffer();
2086 2087
	int			i_attname;
	int			i_typname;
2088
	int			i_atttypmod;
2089
	int			i_attnotnull;
V
Vadim B. Mikheev 已提交
2090
	int			i_atthasdef;
2091 2092
	int			i_attoid;
	PGresult   *res;
2093
	int			ntups;
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108

	for (i = 0; i < numTables; i++)
	{

		if (tblinfo[i].sequence)
			continue;

		/* find all the user attributes and their types */
		/* we must read the attribute names in attribute number order! */

		/*
		 * because we will use the attnum to index into the attnames array
		 * later
		 */
		if (g_verbose)
2109
			fprintf(stderr, "%s finding the attrs and types for table: '%s' %s\n",
2110 2111 2112 2113
					g_comment_start,
					tblinfo[i].relname,
					g_comment_end);

B
Hi, all  
Bruce Momjian 已提交
2114
		resetPQExpBuffer(q);
B
Bruce,  
Bruce Momjian 已提交
2115
		appendPQExpBuffer(q, "SELECT a.oid as attoid, a.attnum, a.attname, t.typname, a.atttypmod, "
2116 2117 2118 2119 2120
						  "a.attnotnull, a.atthasdef "
						  "from pg_attribute a, pg_type t "
				   "where a.attrelid = '%s'::oid and a.atttypid = t.oid "
						  "and a.attnum > 0 order by attnum",
						  tblinfo[i].oid);
B
Hi, all  
Bruce Momjian 已提交
2121
		res = PQexec(g_conn, q->data);
2122 2123 2124
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
B
Bruce Momjian 已提交
2125
			fprintf(stderr, "getTableAttrs(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
2126 2127 2128 2129 2130
			exit_nicely(g_conn);
		}

		ntups = PQntuples(res);

B
Bruce,  
Bruce Momjian 已提交
2131
		i_attoid = PQfnumber(res, "attoid");
2132 2133
		i_attname = PQfnumber(res, "attname");
		i_typname = PQfnumber(res, "typname");
2134
		i_atttypmod = PQfnumber(res, "atttypmod");
2135
		i_attnotnull = PQfnumber(res, "attnotnull");
V
Vadim B. Mikheev 已提交
2136
		i_atthasdef = PQfnumber(res, "atthasdef");
2137 2138

		tblinfo[i].numatts = ntups;
B
Bruce,  
Bruce Momjian 已提交
2139
		tblinfo[i].attoids = (char **) malloc(ntups * sizeof(char *));
2140 2141
		tblinfo[i].attnames = (char **) malloc(ntups * sizeof(char *));
		tblinfo[i].typnames = (char **) malloc(ntups * sizeof(char *));
2142
		tblinfo[i].atttypmod = (int *) malloc(ntups * sizeof(int));
2143 2144
		tblinfo[i].inhAttrs = (int *) malloc(ntups * sizeof(int));
		tblinfo[i].notnull = (bool *) malloc(ntups * sizeof(bool));
V
Vadim B. Mikheev 已提交
2145
		tblinfo[i].adef_expr = (char **) malloc(ntups * sizeof(char *));
2146 2147 2148 2149
		tblinfo[i].parentRels = NULL;
		tblinfo[i].numParents = 0;
		for (j = 0; j < ntups; j++)
		{
B
Bruce,  
Bruce Momjian 已提交
2150
			tblinfo[i].attoids[j] = strdup(PQgetvalue(res, j, i_attoid));
2151 2152
			tblinfo[i].attnames[j] = strdup(PQgetvalue(res, j, i_attname));
			tblinfo[i].typnames[j] = strdup(PQgetvalue(res, j, i_typname));
2153
			tblinfo[i].atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
2154 2155 2156
			tblinfo[i].inhAttrs[j] = 0; /* this flag is set in
										 * flagInhAttrs() */
			tblinfo[i].notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't') ? true : false;
V
Vadim B. Mikheev 已提交
2157 2158 2159
			if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
			{
				PGresult   *res2;
2160

V
Vadim B. Mikheev 已提交
2161
				if (g_verbose)
2162
					fprintf(stderr, "%s finding DEFAULT expression for attr: '%s' %s\n",
V
Vadim B. Mikheev 已提交
2163 2164 2165
							g_comment_start,
							tblinfo[i].attnames[j],
							g_comment_end);
2166

B
Hi, all  
Bruce Momjian 已提交
2167 2168
				resetPQExpBuffer(q);
				appendPQExpBuffer(q, "SELECT adsrc from pg_attrdef "
2169 2170
							 "where adrelid = '%s'::oid and adnum = %d ",
								  tblinfo[i].oid, j + 1);
B
Hi, all  
Bruce Momjian 已提交
2171
				res2 = PQexec(g_conn, q->data);
V
Vadim B. Mikheev 已提交
2172
				if (!res2 ||
2173
					PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
2174
				{
B
Bruce Momjian 已提交
2175
					fprintf(stderr, "getTableAttrs(): SELECT (for DEFAULT) failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
V
Vadim B. Mikheev 已提交
2176 2177 2178 2179 2180 2181 2182
					exit_nicely(g_conn);
				}
				tblinfo[i].adef_expr[j] = strdup(PQgetvalue(res2, 0, PQfnumber(res2, "adsrc")));
				PQclear(res2);
			}
			else
				tblinfo[i].adef_expr[j] = NULL;
2183 2184 2185
		}
		PQclear(res);
	}
2186 2187 2188 2189 2190
}


/*
 * getIndices
2191
 *	  read all the user-defined indices information
2192 2193
 * from the system catalogs return them in the InhInfo* structure
 *
2194 2195
 * numIndices is set to the number of indices read in
 *
2196 2197
 *
 */
2198
IndInfo    *
2199 2200
getIndices(int *numIndices)
{
2201
	int			i;
2202
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
2203
	PGresult   *res;
2204
	int			ntups;
B
Bruce Momjian 已提交
2205
	IndInfo    *indinfo;
2206 2207 2208 2209 2210 2211 2212 2213

	int			i_indexrelname;
	int			i_indrelname;
	int			i_indamname;
	int			i_indproc;
	int			i_indkey;
	int			i_indclass;
	int			i_indisunique;
2214
	int			i_indoid;
2215 2216 2217 2218 2219

	/*
	 * find all the user-defined indices. We do not handle partial
	 * indices.
	 *
2220
	 * Notice we skip indices on inversion objects (relkind 'l')
2221 2222 2223 2224
	 *
	 * this is a 4-way join !!
	 */

B
Hi, all  
Bruce Momjian 已提交
2225
	appendPQExpBuffer(query,
2226 2227 2228 2229 2230 2231 2232 2233
					  "SELECT t1.oid as indoid, t1.relname as indexrelname, t2.relname as indrelname, "
					  "i.indproc, i.indkey, i.indclass, "
					  "a.amname as indamname, i.indisunique "
					"from pg_index i, pg_class t1, pg_class t2, pg_am a "
				   "WHERE t1.oid = i.indexrelid and t2.oid = i.indrelid "
					  "and t1.relam = a.oid and i.indexrelid > '%u'::oid "
					  "and t2.relname !~ '^pg_' and t2.relkind != 'l' and not i.indisprimary",
					  g_last_builtin_oid);
2234

B
Hi, all  
Bruce Momjian 已提交
2235
	res = PQexec(g_conn, query->data);
2236 2237 2238
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
2239
		fprintf(stderr, "getIndices(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
2240 2241 2242 2243 2244 2245 2246 2247 2248
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numIndices = ntups;

	indinfo = (IndInfo *) malloc(ntups * sizeof(IndInfo));

2249 2250
	memset((char *) indinfo, 0, ntups * sizeof(IndInfo));

B
Bruce,  
Bruce Momjian 已提交
2251
	i_indoid = PQfnumber(res, "indoid");
2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
	i_indexrelname = PQfnumber(res, "indexrelname");
	i_indrelname = PQfnumber(res, "indrelname");
	i_indamname = PQfnumber(res, "indamname");
	i_indproc = PQfnumber(res, "indproc");
	i_indkey = PQfnumber(res, "indkey");
	i_indclass = PQfnumber(res, "indclass");
	i_indisunique = PQfnumber(res, "indisunique");

	for (i = 0; i < ntups; i++)
	{
B
Bruce,  
Bruce Momjian 已提交
2262
		indinfo[i].indoid = strdup(PQgetvalue(res, i, i_indoid));
2263 2264 2265 2266
		indinfo[i].indexrelname = strdup(PQgetvalue(res, i, i_indexrelname));
		indinfo[i].indrelname = strdup(PQgetvalue(res, i, i_indrelname));
		indinfo[i].indamname = strdup(PQgetvalue(res, i, i_indamname));
		indinfo[i].indproc = strdup(PQgetvalue(res, i, i_indproc));
2267 2268 2269 2270 2271 2272
		parseNumericArray(PQgetvalue(res, i, i_indkey),
						  indinfo[i].indkey,
						  INDEX_MAX_KEYS);
		parseNumericArray(PQgetvalue(res, i, i_indclass),
						  indinfo[i].indclass,
						  INDEX_MAX_KEYS);
2273 2274 2275 2276
		indinfo[i].indisunique = strdup(PQgetvalue(res, i, i_indisunique));
	}
	PQclear(res);
	return indinfo;
2277 2278
}

B
Bruce,  
Bruce Momjian 已提交
2279
/*------------------------------------------------------------------
2280
 * dumpComments --
B
Bruce,  
Bruce Momjian 已提交
2281
 *
2282
 * This routine is used to dump any comments associated with the
B
Bruce,  
Bruce Momjian 已提交
2283 2284 2285 2286
 * oid handed to this routine. The routine takes a constant character
 * string for the target part of the object and the oid of the object
 * whose comments are to be dumped. It is perfectly acceptable
 * to hand an oid to this routine which has not been commented. In
2287
 * addition, the routine takes the stdio FILE handle to which the
B
Bruce,  
Bruce Momjian 已提交
2288 2289 2290 2291
 * output should be written.
 *------------------------------------------------------------------
*/

T
Tom Lane 已提交
2292
static void
2293 2294
dumpComment(FILE *fout, const char *target, const char *oid)
{
B
Bruce,  
Bruce Momjian 已提交
2295

2296
	PGresult   *res;
B
Bruce,  
Bruce Momjian 已提交
2297
	PQExpBuffer query;
2298
	int			i_description;
B
Bruce,  
Bruce Momjian 已提交
2299 2300 2301 2302 2303 2304 2305 2306 2307 2308

	/*** Build query to find comment ***/

	query = createPQExpBuffer();
	appendPQExpBuffer(query, "SELECT description FROM pg_description WHERE objoid = ");
	appendPQExpBuffer(query, oid);

	/*** Execute query ***/

	res = PQexec(g_conn, query->data);
2309 2310
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce,  
Bruce Momjian 已提交
2311 2312 2313 2314 2315 2316 2317
		fprintf(stderr, "DumpComment: SELECT failed: '%s'.\n",
				PQerrorMessage(g_conn));
		exit_nicely(g_conn);
	}

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

2318 2319
	if (PQntuples(res) != 0)
	{
B
Bruce,  
Bruce Momjian 已提交
2320
		i_description = PQfnumber(res, "description");
2321
		fprintf(fout, "COMMENT ON %s IS '%s';\n",
B
Bruce,  
Bruce Momjian 已提交
2322 2323 2324 2325 2326 2327
				target, checkForQuote(PQgetvalue(res, 0, i_description)));
	}

	/*** Clear the statement buffer and return ***/

	PQclear(res);
2328

B
Bruce,  
Bruce Momjian 已提交
2329 2330 2331
}

/*------------------------------------------------------------------
2332
 * dumpDBComment --
B
Bruce,  
Bruce Momjian 已提交
2333
 *
2334 2335
 * This routine is used to dump any comments associated with the
 * database to which we are currently connected. If the user chose
B
Bruce,  
Bruce Momjian 已提交
2336 2337 2338 2339 2340
 * to dump the schema of the database, then this is the first
 * statement issued.
 *------------------------------------------------------------------
*/

2341 2342 2343
void
dumpDBComment(FILE *fout)
{
B
Bruce,  
Bruce Momjian 已提交
2344

2345
	PGresult   *res;
B
Bruce,  
Bruce Momjian 已提交
2346
	PQExpBuffer query;
2347
	int			i_oid;
B
Bruce,  
Bruce Momjian 已提交
2348 2349 2350 2351 2352 2353 2354 2355 2356 2357

	/*** Build query to find comment ***/

	query = createPQExpBuffer();
	appendPQExpBuffer(query, "SELECT oid FROM pg_database WHERE datname = '%s'",
					  PQdb(g_conn));

	/*** Execute query ***/

	res = PQexec(g_conn, query->data);
2358 2359
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce,  
Bruce Momjian 已提交
2360 2361 2362 2363 2364 2365 2366
		fprintf(stderr, "dumpDBComment: SELECT failed: '%s'.\n",
				PQerrorMessage(g_conn));
		exit_nicely(g_conn);
	}

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

2367 2368
	if (PQntuples(res) != 0)
	{
B
Bruce,  
Bruce Momjian 已提交
2369 2370 2371 2372 2373 2374 2375 2376 2377
		i_oid = PQfnumber(res, "oid");
		resetPQExpBuffer(query);
		appendPQExpBuffer(query, "DATABASE %s", fmtId(PQdb(g_conn), force_quotes));
		dumpComment(fout, query->data, PQgetvalue(res, 0, i_oid));
	}

	/*** Clear the statement buffer and return ***/

	PQclear(res);
2378

B
Bruce,  
Bruce Momjian 已提交
2379 2380
}

2381 2382
/*
 * dumpTypes
2383
 *	  writes out to fout the queries to recreate all the user-defined types
2384 2385 2386
 *
 */
void
2387 2388
dumpTypes(FILE *fout, FuncInfo *finfo, int numFuncs,
		  TypeInfo *tinfo, int numTypes)
2389
{
2390
	int			i;
2391
	PQExpBuffer q = createPQExpBuffer();
2392
	int			funcInd;
2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421

	for (i = 0; i < numTypes; i++)
	{

		/* skip all the builtin types */
		if (atoi(tinfo[i].oid) < g_last_builtin_oid)
			continue;

		/* skip relation types */
		if (atoi(tinfo[i].typrelid) != 0)
			continue;

		/* skip all array types that start w/ underscore */
		if ((tinfo[i].typname[0] == '_') &&
			(strcmp(tinfo[i].typinput, "array_in") == 0))
			continue;

		/*
		 * before we create a type, we need to create the input and output
		 * functions for it, if they haven't been created already
		 */
		funcInd = findFuncByName(finfo, numFuncs, tinfo[i].typinput);
		if (funcInd != -1)
			dumpOneFunc(fout, finfo, funcInd, tinfo, numTypes);

		funcInd = findFuncByName(finfo, numFuncs, tinfo[i].typoutput);
		if (funcInd != -1)
			dumpOneFunc(fout, finfo, funcInd, tinfo, numTypes);

2422
		becomeUser(fout, tinfo[i].usename);
2423

2424
		if (dropSchema)
B
Bruce Momjian 已提交
2425
		{
B
Hi, all  
Bruce Momjian 已提交
2426 2427 2428
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "DROP TYPE %s;\n", fmtId(tinfo[i].typname, force_quotes));
			fputs(q->data, fout);
B
Bruce Momjian 已提交
2429
		}
2430

B
Hi, all  
Bruce Momjian 已提交
2431 2432
		resetPQExpBuffer(q);
		appendPQExpBuffer(q,
2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443
						  "CREATE TYPE %s "
			   "( internallength = %s, externallength = %s, input = %s, "
				  "output = %s, send = %s, receive = %s, default = '%s'",
						  fmtId(tinfo[i].typname, force_quotes),
						  tinfo[i].typlen,
						  tinfo[i].typprtlen,
						  tinfo[i].typinput,
						  tinfo[i].typoutput,
						  tinfo[i].typsend,
						  tinfo[i].typreceive,
						  tinfo[i].typdefault);
2444 2445 2446

		if (tinfo[i].isArray)
		{
2447
			char	   *elemType;
2448 2449 2450

			elemType = findTypeByOid(tinfo, numTypes, tinfo[i].typelem);

B
Hi, all  
Bruce Momjian 已提交
2451
			appendPQExpBuffer(q, ", element = %s, delimiter = '%s'",
2452
							  elemType, tinfo[i].typdelim);
2453 2454
		}
		if (tinfo[i].passedbyvalue)
B
Hi, all  
Bruce Momjian 已提交
2455
			appendPQExpBuffer(q, ",passedbyvalue);\n");
2456
		else
B
Hi, all  
Bruce Momjian 已提交
2457
			appendPQExpBuffer(q, ");\n");
2458

B
Hi, all  
Bruce Momjian 已提交
2459
		fputs(q->data, fout);
B
Bruce,  
Bruce Momjian 已提交
2460 2461 2462 2463 2464 2465 2466

		/*** Dump Type Comments ***/

		resetPQExpBuffer(q);
		appendPQExpBuffer(q, "TYPE %s", fmtId(tinfo[i].typname, force_quotes));
		dumpComment(fout, q->data, tinfo[i].oid);

2467
	}
2468 2469
}

2470 2471
/*
 * dumpProcLangs
B
Bruce Momjian 已提交
2472
 *		  writes out to fout the queries to recreate user-defined procedural languages
2473 2474 2475 2476
 *
 */
void
dumpProcLangs(FILE *fout, FuncInfo *finfo, int numFuncs,
B
Bruce Momjian 已提交
2477
			  TypeInfo *tinfo, int numTypes)
2478
{
2479 2480
	PGresult   *res;
	PQExpBuffer query = createPQExpBuffer();
2481 2482 2483 2484 2485
	int			ntups;
	int			i_lanname;
	int			i_lanpltrusted;
	int			i_lanplcallfoid;
	int			i_lancompiler;
2486 2487 2488
	char	   *lanname;
	char	   *lancompiler;
	const char *lanplcallfoid;
2489 2490 2491
	int			i,
				fidx;

B
Hi, all  
Bruce Momjian 已提交
2492
	appendPQExpBuffer(query, "SELECT * FROM pg_language "
2493 2494
					  "WHERE lanispl "
					  "ORDER BY oid");
B
Hi, all  
Bruce Momjian 已提交
2495
	res = PQexec(g_conn, query->data);
2496 2497 2498
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
2499
		fprintf(stderr, "dumpProcLangs(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
2500 2501 2502 2503
		exit_nicely(g_conn);
	}
	ntups = PQntuples(res);

B
Bruce Momjian 已提交
2504 2505 2506 2507
	i_lanname = PQfnumber(res, "lanname");
	i_lanpltrusted = PQfnumber(res, "lanpltrusted");
	i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
	i_lancompiler = PQfnumber(res, "lancompiler");
2508

B
Bruce Momjian 已提交
2509 2510
	for (i = 0; i < ntups; i++)
	{
2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
		lanplcallfoid = PQgetvalue(res, i, i_lanplcallfoid);
		for (fidx = 0; fidx < numFuncs; fidx++)
		{
			if (!strcmp(finfo[fidx].oid, lanplcallfoid))
				break;
		}
		if (fidx >= numFuncs)
		{
			fprintf(stderr, "dumpProcLangs(): handler procedure for language %s not found\n", PQgetvalue(res, i, i_lanname));
			exit_nicely(g_conn);
		}

		dumpOneFunc(fout, finfo, fidx, tinfo, numTypes);

		lanname = checkForQuote(PQgetvalue(res, i, i_lanname));
		lancompiler = checkForQuote(PQgetvalue(res, i, i_lancompiler));

2528
		if (dropSchema)
B
Bruce Momjian 已提交
2529
			fprintf(fout, "DROP PROCEDURAL LANGUAGE '%s';\n", lanname);
2530

2531
		fprintf(fout, "CREATE %sPROCEDURAL LANGUAGE '%s' "
B
Bruce Momjian 已提交
2532 2533 2534 2535 2536
				"HANDLER %s LANCOMPILER '%s';\n",
		(PQgetvalue(res, i, i_lanpltrusted)[0] == 't') ? "TRUSTED " : "",
				lanname,
				fmtId(finfo[fidx].proname, force_quotes),
				lancompiler);
2537 2538 2539 2540 2541 2542 2543 2544 2545

		free(lanname);
		free(lancompiler);
	}

	PQclear(res);

}

2546 2547
/*
 * dumpFuncs
2548
 *	  writes out to fout the queries to recreate all the user-defined functions
2549 2550 2551
 *
 */
void
2552 2553
dumpFuncs(FILE *fout, FuncInfo *finfo, int numFuncs,
		  TypeInfo *tinfo, int numTypes)
2554
{
2555
	int			i;
2556 2557 2558

	for (i = 0; i < numFuncs; i++)
		dumpOneFunc(fout, finfo, i, tinfo, numTypes);
2559 2560 2561 2562
}

/*
 * dumpOneFunc:
2563 2564
 *	  dump out only one function,  the index of which is given in the third
 *	argument
2565 2566 2567
 *
 */

2568
static void
2569 2570
dumpOneFunc(FILE *fout, FuncInfo *finfo, int i,
			TypeInfo *tinfo, int numTypes)
2571
{
2572
	PQExpBuffer q = createPQExpBuffer();
B
Bruce,  
Bruce Momjian 已提交
2573
	PQExpBuffer fnlist = createPQExpBuffer();
B
Bruce Momjian 已提交
2574
	int			j;
2575
	char	   *func_def;
2576
	char		func_lang[NAMEDATALEN + 1];
2577 2578 2579 2580
	PGresult   *res;
	int			nlangs;
	int			i_lanname;
	char		query[256];
2581 2582 2583 2584 2585 2586

	if (finfo[i].dumped)
		return;
	else
		finfo[i].dumped = 1;

2587
	becomeUser(fout, finfo[i].usename);
2588

2589 2590 2591 2592 2593
	sprintf(query, "SELECT lanname FROM pg_language WHERE oid = %u",
			finfo[i].lang);
	res = PQexec(g_conn, query);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
2594
	{
2595 2596
		fprintf(stderr, "dumpOneFunc(): SELECT for procedural language failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
		exit_nicely(g_conn);
2597
	}
2598 2599 2600
	nlangs = PQntuples(res);

	if (nlangs != 1)
2601
	{
2602 2603
		fprintf(stderr, "dumpOneFunc(): procedural language for function %s not found\n", finfo[i].proname);
		exit_nicely(g_conn);
2604 2605
	}

2606
	i_lanname = PQfnumber(res, "lanname");
2607

2608 2609
	func_def = finfo[i].prosrc;
	strcpy(func_lang, PQgetvalue(res, 0, i_lanname));
2610

2611
	PQclear(res);
2612

2613
	if (dropSchema)
B
Bruce Momjian 已提交
2614
	{
B
Hi, all  
Bruce Momjian 已提交
2615 2616
		resetPQExpBuffer(q);
		appendPQExpBuffer(q, "DROP FUNCTION %s (", fmtId(finfo[i].proname, force_quotes));
B
Bruce Momjian 已提交
2617 2618 2619 2620 2621
		for (j = 0; j < finfo[i].nargs; j++)
		{
			char	   *typname;

			typname = findTypeByOid(tinfo, numTypes, finfo[i].argtypes[j]);
B
Hi, all  
Bruce Momjian 已提交
2622
			appendPQExpBuffer(q, "%s%s",
2623 2624
							  (j > 0) ? "," : "",
							  fmtId(typname, false));
B
Bruce Momjian 已提交
2625
		}
B
Hi, all  
Bruce Momjian 已提交
2626 2627
		appendPQExpBuffer(q, ");\n");
		fputs(q->data, fout);
B
Bruce Momjian 已提交
2628
	}
2629

B
Hi, all  
Bruce Momjian 已提交
2630 2631
	resetPQExpBuffer(q);
	appendPQExpBuffer(q, "CREATE FUNCTION %s (", fmtId(finfo[i].proname, force_quotes));
2632 2633
	for (j = 0; j < finfo[i].nargs; j++)
	{
2634
		char	   *typname;
2635 2636

		typname = findTypeByOid(tinfo, numTypes, finfo[i].argtypes[j]);
B
Hi, all  
Bruce Momjian 已提交
2637
		appendPQExpBuffer(q, "%s%s",
2638 2639
						  (j > 0) ? "," : "",
						  fmtId(typname, false));
B
Bruce,  
Bruce Momjian 已提交
2640 2641 2642
		appendPQExpBuffer(fnlist, "%s%s",
						  (j > 0) ? "," : "",
						  fmtId(typname, false));
2643
	}
B
Hi, all  
Bruce Momjian 已提交
2644
	appendPQExpBuffer(q, " ) RETURNS %s%s AS '%s' LANGUAGE '%s';\n",
2645 2646 2647
					  (finfo[i].retset) ? " SETOF " : "",
	   fmtId(findTypeByOid(tinfo, numTypes, finfo[i].prorettype), false),
					  func_def, func_lang);
2648

B
Hi, all  
Bruce Momjian 已提交
2649
	fputs(q->data, fout);
2650

B
Bruce,  
Bruce Momjian 已提交
2651 2652 2653 2654 2655 2656 2657 2658
	/*** Dump Function Comments ***/

	resetPQExpBuffer(q);
	appendPQExpBuffer(q, "FUNCTION %s ",
					  fmtId(finfo[i].proname, force_quotes));
	appendPQExpBuffer(q, "( %s )", fnlist->data);
	dumpComment(fout, q->data, finfo[i].oid);

2659 2660 2661 2662
}

/*
 * dumpOprs
2663
 *	  writes out to fout the queries to recreate all the user-defined operators
2664 2665
 *
 */
2666
void
2667 2668
dumpOprs(FILE *fout, OprInfo *oprinfo, int numOperators,
		 TypeInfo *tinfo, int numTypes)
2669
{
B
Bruce Momjian 已提交
2670
	int			i;
2671 2672 2673 2674 2675 2676 2677 2678 2679
	PQExpBuffer q = createPQExpBuffer();
	PQExpBuffer leftarg = createPQExpBuffer();
	PQExpBuffer rightarg = createPQExpBuffer();
	PQExpBuffer commutator = createPQExpBuffer();
	PQExpBuffer negator = createPQExpBuffer();
	PQExpBuffer restrictor = createPQExpBuffer();
	PQExpBuffer join = createPQExpBuffer();
	PQExpBuffer sort1 = createPQExpBuffer();
	PQExpBuffer sort2 = createPQExpBuffer();
2680 2681 2682 2683

	for (i = 0; i < numOperators; i++)
	{

B
Hi, all  
Bruce Momjian 已提交
2684 2685 2686 2687 2688 2689 2690 2691 2692
		resetPQExpBuffer(leftarg);
		resetPQExpBuffer(rightarg);
		resetPQExpBuffer(commutator);
		resetPQExpBuffer(negator);
		resetPQExpBuffer(restrictor);
		resetPQExpBuffer(join);
		resetPQExpBuffer(sort1);
		resetPQExpBuffer(sort2);

2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710
		/* skip all the builtin oids */
		if (atoi(oprinfo[i].oid) < g_last_builtin_oid)
			continue;

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

		/*
		 * right unary means there's a left arg and left unary means
		 * there's a right arg
		 */
		if (strcmp(oprinfo[i].oprkind, "r") == 0 ||
			strcmp(oprinfo[i].oprkind, "b") == 0)
		{
B
Hi, all  
Bruce Momjian 已提交
2711
			appendPQExpBuffer(leftarg, ",\n\tLEFTARG = %s ",
2712
							  fmtId(findTypeByOid(tinfo, numTypes, oprinfo[i].oprleft), false));
2713 2714 2715 2716
		}
		if (strcmp(oprinfo[i].oprkind, "l") == 0 ||
			strcmp(oprinfo[i].oprkind, "b") == 0)
		{
B
Hi, all  
Bruce Momjian 已提交
2717
			appendPQExpBuffer(rightarg, ",\n\tRIGHTARG = %s ",
2718
							  fmtId(findTypeByOid(tinfo, numTypes, oprinfo[i].oprright), false));
2719
		}
B
Hi, all  
Bruce Momjian 已提交
2720 2721
		if (!(strcmp(oprinfo[i].oprcom, "0") == 0))
			appendPQExpBuffer(commutator, ",\n\tCOMMUTATOR = %s ",
2722 2723
				 findOprByOid(oprinfo, numOperators, oprinfo[i].oprcom));

B
Hi, all  
Bruce Momjian 已提交
2724 2725
		if (!(strcmp(oprinfo[i].oprnegate, "0") == 0))
			appendPQExpBuffer(negator, ",\n\tNEGATOR = %s ",
2726 2727
			  findOprByOid(oprinfo, numOperators, oprinfo[i].oprnegate));

B
Hi, all  
Bruce Momjian 已提交
2728 2729
		if (!(strcmp(oprinfo[i].oprrest, "-") == 0))
			appendPQExpBuffer(restrictor, ",\n\tRESTRICT = %s ", oprinfo[i].oprrest);
2730

B
Hi, all  
Bruce Momjian 已提交
2731 2732
		if (!(strcmp(oprinfo[i].oprjoin, "-") == 0))
			appendPQExpBuffer(join, ",\n\tJOIN = %s ", oprinfo[i].oprjoin);
2733

B
Hi, all  
Bruce Momjian 已提交
2734 2735
		if (!(strcmp(oprinfo[i].oprlsortop, "0") == 0))
			appendPQExpBuffer(sort1, ",\n\tSORT1 = %s ",
B
Bruce Momjian 已提交
2736
			 findOprByOid(oprinfo, numOperators, oprinfo[i].oprlsortop));
2737

B
Hi, all  
Bruce Momjian 已提交
2738 2739
		if (!(strcmp(oprinfo[i].oprrsortop, "0") == 0))
			appendPQExpBuffer(sort2, ",\n\tSORT2 = %s ",
B
Bruce Momjian 已提交
2740
			 findOprByOid(oprinfo, numOperators, oprinfo[i].oprrsortop));
2741

2742
		becomeUser(fout, oprinfo[i].usename);
2743

2744
		if (dropSchema)
B
Bruce Momjian 已提交
2745
		{
B
Hi, all  
Bruce Momjian 已提交
2746
			resetPQExpBuffer(q);
2747
			appendPQExpBuffer(q, "DROP OPERATOR %s (%s", oprinfo[i].oprname,
2748 2749
				fmtId(findTypeByOid(tinfo, numTypes, oprinfo[i].oprleft),
					  false));
2750
			appendPQExpBuffer(q, ", %s);\n",
2751 2752
			   fmtId(findTypeByOid(tinfo, numTypes, oprinfo[i].oprright),
					 false));
B
Hi, all  
Bruce Momjian 已提交
2753
			fputs(q->data, fout);
B
Bruce Momjian 已提交
2754
		}
2755

B
Hi, all  
Bruce Momjian 已提交
2756 2757
		resetPQExpBuffer(q);
		appendPQExpBuffer(q,
2758 2759 2760 2761 2762 2763 2764 2765 2766
						  "CREATE OPERATOR %s "
						  "(PROCEDURE = %s %s%s%s%s%s%s%s%s%s);\n",
						  oprinfo[i].oprname,
						  oprinfo[i].oprcode,
						  leftarg->data,
						  rightarg->data,
						  commutator->data,
						  negator->data,
						  restrictor->data,
B
Bruce Momjian 已提交
2767
		  (strcmp(oprinfo[i].oprcanhash, "t") == 0) ? ",\n\tHASHES" : "",
2768 2769 2770
						  join->data,
						  sort1->data,
						  sort2->data);
2771

B
Hi, all  
Bruce Momjian 已提交
2772
		fputs(q->data, fout);
2773
	}
2774 2775 2776 2777
}

/*
 * dumpAggs
2778
 *	  writes out to fout the queries to create all the user-defined aggregates
2779 2780 2781
 *
 */
void
2782 2783
dumpAggs(FILE *fout, AggInfo *agginfo, int numAggs,
		 TypeInfo *tinfo, int numTypes)
2784
{
B
Bruce Momjian 已提交
2785
	int			i;
2786 2787 2788 2789 2790
	PQExpBuffer q = createPQExpBuffer();
	PQExpBuffer sfunc1 = createPQExpBuffer();
	PQExpBuffer sfunc2 = createPQExpBuffer();
	PQExpBuffer basetype = createPQExpBuffer();
	PQExpBuffer finalfunc = createPQExpBuffer();
2791
	char		comma1[2],
B
Bruce Momjian 已提交
2792
				comma2[2];
2793 2794 2795

	for (i = 0; i < numAggs; i++)
	{
B
Hi, all  
Bruce Momjian 已提交
2796 2797 2798 2799 2800 2801

		resetPQExpBuffer(sfunc1);
		resetPQExpBuffer(sfunc2);
		resetPQExpBuffer(basetype);
		resetPQExpBuffer(finalfunc);

2802 2803 2804
		/* skip all the builtin oids */
		if (atoi(agginfo[i].oid) < g_last_builtin_oid)
			continue;
2805

B
Hi, all  
Bruce Momjian 已提交
2806
		appendPQExpBuffer(basetype,
2807 2808
						  "BASETYPE = %s, ",
						  fmtId(findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype), false));
2809

B
Hi, all  
Bruce Momjian 已提交
2810
		if (!(strcmp(agginfo[i].aggtransfn1, "-") == 0))
2811
		{
B
Hi, all  
Bruce Momjian 已提交
2812
			appendPQExpBuffer(sfunc1,
2813 2814 2815
							  "SFUNC1 = %s, STYPE1 = %s",
							  agginfo[i].aggtransfn1,
							  fmtId(findTypeByOid(tinfo, numTypes, agginfo[i].aggtranstype1), false));
2816
			if (agginfo[i].agginitval1)
B
Hi, all  
Bruce Momjian 已提交
2817
				appendPQExpBuffer(sfunc1, ", INITCOND1 = '%s'",
2818
								  agginfo[i].agginitval1);
2819 2820 2821

		}

B
Hi, all  
Bruce Momjian 已提交
2822
		if (!(strcmp(agginfo[i].aggtransfn2, "-") == 0))
2823
		{
B
Hi, all  
Bruce Momjian 已提交
2824
			appendPQExpBuffer(sfunc2,
2825 2826 2827
							  "SFUNC2 = %s, STYPE2 = %s",
							  agginfo[i].aggtransfn2,
							  fmtId(findTypeByOid(tinfo, numTypes, agginfo[i].aggtranstype2), false));
2828
			if (agginfo[i].agginitval2)
B
Hi, all  
Bruce Momjian 已提交
2829
				appendPQExpBuffer(sfunc2, ", INITCOND2 = '%s'",
2830
								  agginfo[i].agginitval2);
2831 2832
		}

B
Hi, all  
Bruce Momjian 已提交
2833 2834 2835
		if (!(strcmp(agginfo[i].aggfinalfn, "-") == 0))
			appendPQExpBuffer(finalfunc, "FINALFUNC = %s", agginfo[i].aggfinalfn);
		if (sfunc1->data[0] != '\0' && sfunc2->data[0] != '\0')
2836 2837 2838 2839 2840 2841 2842
		{
			comma1[0] = ',';
			comma1[1] = '\0';
		}
		else
			comma1[0] = '\0';

B
Hi, all  
Bruce Momjian 已提交
2843
		if (finalfunc->data[0] != '\0' && (sfunc1->data[0] != '\0' || sfunc2->data[0] != '\0'))
2844 2845 2846 2847 2848 2849 2850
		{
			comma2[0] = ',';
			comma2[1] = '\0';
		}
		else
			comma2[0] = '\0';

2851
		becomeUser(fout, agginfo[i].usename);
2852

2853
		if (dropSchema)
B
Bruce Momjian 已提交
2854
		{
B
Hi, all  
Bruce Momjian 已提交
2855 2856
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "DROP AGGREGATE %s %s;\n", agginfo[i].aggname,
2857
							  fmtId(findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype), false));
B
Hi, all  
Bruce Momjian 已提交
2858
			fputs(q->data, fout);
B
Bruce Momjian 已提交
2859
		}
2860

B
Hi, all  
Bruce Momjian 已提交
2861 2862
		resetPQExpBuffer(q);
		appendPQExpBuffer(q, "CREATE AGGREGATE %s ( %s %s%s %s%s %s );\n",
2863 2864 2865 2866 2867 2868 2869
						  agginfo[i].aggname,
						  basetype->data,
						  sfunc1->data,
						  comma1,
						  sfunc2->data,
						  comma2,
						  finalfunc->data);
2870

B
Hi, all  
Bruce Momjian 已提交
2871
		fputs(q->data, fout);
B
Bruce,  
Bruce Momjian 已提交
2872 2873 2874 2875

		/*** Dump Aggregate Comments ***/

		resetPQExpBuffer(q);
2876
		appendPQExpBuffer(q, "AGGREGATE %s %s", agginfo[i].aggname,
B
Bruce,  
Bruce Momjian 已提交
2877 2878 2879
						  fmtId(findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype), false));
		dumpComment(fout, q->data, agginfo[i].oid);

2880
	}
2881 2882
}

2883 2884 2885 2886 2887
/*
 * These are some support functions to fix the acl problem of pg_dump
 *
 * Matthew C. Aycock 12/02/97
 */
2888 2889 2890

/* Append a keyword to a keyword list, inserting comma if needed.
 * Caller must make aclbuf big enough for all possible keywords.
2891
 */
2892
static void
B
Bruce Momjian 已提交
2893
AddAcl(char *aclbuf, const char *keyword)
2894
{
2895 2896 2897
	if (*aclbuf)
		strcat(aclbuf, ",");
	strcat(aclbuf, keyword);
2898
}
2899

2900
/*
2901
 * This will take a string of 'arwR' and return a malloced,
2902 2903
 * comma delimited string of SELECT,INSERT,UPDATE,DELETE,RULE
 */
V
Vadim B. Mikheev 已提交
2904
static char *
2905
GetPrivileges(const char *s)
2906
{
2907
	char		aclbuf[100];
2908

2909
	aclbuf[0] = '\0';
2910

B
Bruce Momjian 已提交
2911
	if (strchr(s, 'a'))
2912
		AddAcl(aclbuf, "INSERT");
2913

B
Bruce Momjian 已提交
2914
	if (strchr(s, 'w'))
2915
		AddAcl(aclbuf, "UPDATE,DELETE");
B
Bruce Momjian 已提交
2916 2917

	if (strchr(s, 'r'))
2918
		AddAcl(aclbuf, "SELECT");
2919

2920
	if (strchr(s, 'R'))
2921
		AddAcl(aclbuf, "RULE");
2922

2923 2924 2925
	/* Special-case when they're all there */
	if (strcmp(aclbuf, "INSERT,UPDATE,DELETE,SELECT,RULE") == 0)
		return strdup("ALL");
2926

2927
	return strdup(aclbuf);
2928
}
2929

B
Bruce Momjian 已提交
2930 2931
/*
 * dumpACL:
2932 2933
 *	  Write out grant/revoke information
 *	  Called for sequences and tables
B
Bruce Momjian 已提交
2934 2935
 */

2936
static void
B
Bruce Momjian 已提交
2937 2938
dumpACL(FILE *fout, TableInfo tbinfo)
{
2939 2940
	const char *acls = tbinfo.relacl;
	char	   *aclbuf,
B
Bruce Momjian 已提交
2941 2942 2943
			   *tok,
			   *eqpos,
			   *priv;
2944 2945 2946 2947

	if (strlen(acls) == 0)
		return;					/* table has default permissions */

B
Bruce Momjian 已提交
2948 2949 2950
	/*
	 * Revoke Default permissions for PUBLIC. Is this actually necessary,
	 * or is it just a waste of time?
2951 2952 2953
	 */
	fprintf(fout,
			"REVOKE ALL on %s from PUBLIC;\n",
2954
			fmtId(tbinfo.relname, force_quotes));
2955 2956 2957

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

2959 2960
	/* Scan comma-separated ACL items */
	for (tok = strtok(aclbuf, ","); tok != NULL; tok = strtok(NULL, ","))
2961
	{
2962

B
Bruce Momjian 已提交
2963 2964 2965
		/*
		 * Token may start with '{' and/or '"'.  Actually only the start
		 * of the string should have '{', but we don't verify that.
2966 2967 2968 2969 2970 2971 2972 2973
		 */
		if (*tok == '{')
			tok++;
		if (*tok == '"')
			tok++;

		/* User name is string up to = in tok */
		eqpos = strchr(tok, '=');
B
Bruce Momjian 已提交
2974
		if (!eqpos)
B
Bruce Momjian 已提交
2975
		{
2976
			fprintf(stderr, "Could not parse ACL list for '%s'...Exiting!\n",
B
Bruce Momjian 已提交
2977 2978 2979 2980
					tbinfo.relname);
			exit_nicely(g_conn);
		}

B
Bruce Momjian 已提交
2981 2982 2983 2984
		/*
		 * Parse the privileges (right-hand side).	Skip if there are
		 * none.
		 */
2985 2986
		priv = GetPrivileges(eqpos + 1);
		if (*priv)
2987
		{
2988 2989
			fprintf(fout,
					"GRANT %s on %s to ",
2990
					priv, fmtId(tbinfo.relname, force_quotes));
B
Bruce Momjian 已提交
2991 2992 2993

			/*
			 * Note: fmtId() can only be called once per printf, so don't
2994 2995 2996 2997 2998
			 * try to merge printing of username into the above printf.
			 */
			if (eqpos == tok)
			{
				/* Empty left-hand side means "PUBLIC" */
2999
				fprintf(fout, "PUBLIC;\n");
3000
			}
3001
			else
3002 3003
			{
				*eqpos = '\0';	/* it's ok to clobber aclbuf */
3004 3005 3006 3007 3008
				if (strncmp(tok, "group ", strlen("group ")) == 0)
					fprintf(fout, "GROUP %s;\n",
							fmtId(tok + strlen("group "), force_quotes));
				else
					fprintf(fout, "%s;\n", fmtId(tok, force_quotes));
3009
			}
3010
		}
3011
		free(priv);
B
Bruce Momjian 已提交
3012
	}
3013 3014

	free(aclbuf);
B
Bruce Momjian 已提交
3015 3016
}

3017

3018 3019
/*
 * dumpTables:
3020
 *	  write out to fout all the user-define tables
3021
 */
3022

3023
void
3024 3025 3026
dumpTables(FILE *fout, TableInfo *tblinfo, int numTables,
		   InhInfo *inhinfo, int numInherits,
		   TypeInfo *tinfo, int numTypes, const char *tablename,
3027
		   const bool aclsSkip)
3028
{
3029 3030
	int			i,
				j,
B
Bruce Momjian 已提交
3031
				k;
3032 3033
	PQExpBuffer q = createPQExpBuffer();
	char	   *serialSeq = NULL;		/* implicit sequence name created
B
Bruce Momjian 已提交
3034 3035 3036 3037
										 * by SERIAL datatype */
	const char *serialSeqSuffix = "_id_seq";	/* suffix for implicit
												 * SERIAL sequences */
	char	  **parentRels;		/* list of names of parent relations */
3038
	int			numParents;
B
Bruce Momjian 已提交
3039 3040
	int			actual_atts;	/* number of attrs in this CREATE statment */
	int32		tmp_typmod;
3041 3042 3043
	int			precision;
	int			scale;

3044

V
Vadim B. Mikheev 已提交
3045
	/* First - dump SEQUENCEs */
B
Bruce Momjian 已提交
3046
	if (tablename)
B
Bruce Momjian 已提交
3047 3048 3049 3050 3051
	{
		serialSeq = malloc(strlen(tablename) + strlen(serialSeqSuffix) + 1);
		strcpy(serialSeq, tablename);
		strcat(serialSeq, serialSeqSuffix);
	}
V
Vadim B. Mikheev 已提交
3052 3053 3054 3055
	for (i = 0; i < numTables; i++)
	{
		if (!(tblinfo[i].sequence))
			continue;
B
Bruce Momjian 已提交
3056
		if (!tablename || (!strcmp(tblinfo[i].relname, tablename))
B
Bruce Momjian 已提交
3057
			|| (serialSeq && !strcmp(tblinfo[i].relname, serialSeq)))
V
Vadim B. Mikheev 已提交
3058
		{
3059
			becomeUser(fout, tblinfo[i].usename);
V
Vadim B. Mikheev 已提交
3060
			dumpSequence(fout, tblinfo[i]);
3061
			if (!aclsSkip)
B
Bruce Momjian 已提交
3062
				dumpACL(fout, tblinfo[i]);
V
Vadim B. Mikheev 已提交
3063 3064
		}
	}
B
Bruce Momjian 已提交
3065
	if (tablename)
B
Bruce Momjian 已提交
3066
		free(serialSeq);
3067

3068 3069
	for (i = 0; i < numTables; i++)
	{
3070
		if (tblinfo[i].sequence)/* already dumped */
V
Vadim B. Mikheev 已提交
3071
			continue;
3072 3073 3074 3075

		if (!tablename || (!strcmp(tblinfo[i].relname, tablename)))
		{

3076
			/* Skip VIEW relations */
B
Bruce Momjian 已提交
3077

3078
			/*
B
Bruce Momjian 已提交
3079 3080
			 * if (isViewRule(tblinfo[i].relname)) continue;
			 */
3081

3082 3083
			parentRels = tblinfo[i].parentRels;
			numParents = tblinfo[i].numParents;
3084

3085
			becomeUser(fout, tblinfo[i].usename);
3086

3087
			if (dropSchema)
B
Bruce Momjian 已提交
3088
			{
B
Hi, all  
Bruce Momjian 已提交
3089 3090 3091
				resetPQExpBuffer(q);
				appendPQExpBuffer(q, "DROP TABLE %s;\n", fmtId(tblinfo[i].relname, force_quotes));
				fputs(q->data, fout);
B
Bruce Momjian 已提交
3092
			}
3093

B
Hi, all  
Bruce Momjian 已提交
3094 3095
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "CREATE TABLE %s (\n\t", fmtId(tblinfo[i].relname, force_quotes));
3096 3097 3098 3099
			actual_atts = 0;
			for (j = 0; j < tblinfo[i].numatts; j++)
			{
				if (tblinfo[i].inhAttrs[j] == 0)
B
Hi all  
Bruce Momjian 已提交
3100
				{
3101
					if (actual_atts > 0)
B
Hi, all  
Bruce Momjian 已提交
3102 3103
						appendPQExpBuffer(q, ",\n\t");
					appendPQExpBuffer(q, "%s ",
3104
							fmtId(tblinfo[i].attnames[j], force_quotes));
3105 3106 3107

					/* Show lengths on bpchar and varchar */
					if (!strcmp(tblinfo[i].typnames[j], "bpchar"))
3108
					{
B
Bruce Momjian 已提交
3109 3110
						int			len = (tblinfo[i].atttypmod[j] - VARHDRSZ);

B
Hi, all  
Bruce Momjian 已提交
3111
						appendPQExpBuffer(q, "character");
3112
						if (len > 1)
B
Hi, all  
Bruce Momjian 已提交
3113
							appendPQExpBuffer(q, "(%d)",
3114
									 tblinfo[i].atttypmod[j] - VARHDRSZ);
3115
					}
3116 3117
					else if (!strcmp(tblinfo[i].typnames[j], "varchar"))
					{
B
Hi, all  
Bruce Momjian 已提交
3118
						appendPQExpBuffer(q, "character varying");
3119 3120
						if (tblinfo[i].atttypmod[j] != -1)
						{
B
Hi, all  
Bruce Momjian 已提交
3121
							appendPQExpBuffer(q, "(%d)",
3122
									 tblinfo[i].atttypmod[j] - VARHDRSZ);
3123
						}
3124
					}
3125 3126
					else if (!strcmp(tblinfo[i].typnames[j], "numeric"))
					{
B
Hi, all  
Bruce Momjian 已提交
3127
						appendPQExpBuffer(q, "numeric");
3128 3129 3130 3131
						if (tblinfo[i].atttypmod[j] != -1)
						{
							tmp_typmod = tblinfo[i].atttypmod[j] - VARHDRSZ;
							precision = (tmp_typmod >> 16) & 0xffff;
B
Bruce Momjian 已提交
3132
							scale = tmp_typmod & 0xffff;
B
Hi, all  
Bruce Momjian 已提交
3133
							appendPQExpBuffer(q, "(%d,%d)",
3134
											  precision, scale);
3135 3136
						}
					}
B
Bruce Momjian 已提交
3137 3138 3139 3140 3141

					/*
					 * char is an internal single-byte data type; Let's
					 * make sure we force it through with quotes. - thomas
					 * 1998-12-13
3142 3143 3144
					 */
					else if (!strcmp(tblinfo[i].typnames[j], "char"))
					{
B
Hi, all  
Bruce Momjian 已提交
3145
						appendPQExpBuffer(q, "%s",
3146
									fmtId(tblinfo[i].typnames[j], true));
3147
					}
3148 3149
					else
					{
B
Hi, all  
Bruce Momjian 已提交
3150
						appendPQExpBuffer(q, "%s",
3151
								   fmtId(tblinfo[i].typnames[j], false));
3152 3153
					}
					if (tblinfo[i].adef_expr[j] != NULL)
B
Hi, all  
Bruce Momjian 已提交
3154
						appendPQExpBuffer(q, " DEFAULT %s",
3155
										  tblinfo[i].adef_expr[j]);
3156
					if (tblinfo[i].notnull[j])
B
Hi, all  
Bruce Momjian 已提交
3157
						appendPQExpBuffer(q, " NOT NULL");
3158
					actual_atts++;
3159
				}
3160
			}
B
Hi all  
Bruce Momjian 已提交
3161

3162 3163 3164
			/* put the CONSTRAINTS inside the table def */
			for (k = 0; k < tblinfo[i].ncheck; k++)
			{
3165
				if (actual_atts + k > 0)
B
Hi, all  
Bruce Momjian 已提交
3166 3167
					appendPQExpBuffer(q, ",\n\t");
				appendPQExpBuffer(q, "%s",
3168
								  tblinfo[i].check_expr[k]);
3169
			}
3170

3171 3172 3173 3174 3175 3176 3177
			/* PRIMARY KEY */
			if (tblinfo[i].primary_key)
			{
				if (actual_atts + tblinfo[i].ncheck > 0)
					appendPQExpBuffer(q, ",\n\t");
				appendPQExpBuffer(q, "PRIMARY KEY (%s)", tblinfo[i].primary_key);
			}
B
Bruce Momjian 已提交
3178

3179
			appendPQExpBuffer(q, "\n)");
3180 3181 3182

			if (numParents > 0)
			{
B
Hi, all  
Bruce Momjian 已提交
3183
				appendPQExpBuffer(q, "\ninherits (");
3184
				for (k = 0; k < numParents; k++)
B
Hi all  
Bruce Momjian 已提交
3185
				{
B
Hi, all  
Bruce Momjian 已提交
3186
					appendPQExpBuffer(q, "%s%s",
3187 3188
									  (k > 0) ? ", " : "",
									  fmtId(parentRels[k], force_quotes));
B
Hi all  
Bruce Momjian 已提交
3189
				}
B
Hi, all  
Bruce Momjian 已提交
3190
				appendPQExpBuffer(q, ")");
3191
			}
B
Hi all  
Bruce Momjian 已提交
3192

B
Hi, all  
Bruce Momjian 已提交
3193 3194
			appendPQExpBuffer(q, ";\n");
			fputs(q->data, fout);
3195
			if (!aclsSkip)
B
Bruce Momjian 已提交
3196
				dumpACL(fout, tblinfo[i]);
3197

3198
			/* Dump Field Comments */
B
Bruce,  
Bruce Momjian 已提交
3199

3200 3201
			for (j = 0; j < tblinfo[i].numatts; j++)
			{
B
Bruce,  
Bruce Momjian 已提交
3202 3203 3204 3205 3206 3207
				resetPQExpBuffer(q);
				appendPQExpBuffer(q, "COLUMN %s", fmtId(tblinfo[i].relname, force_quotes));
				appendPQExpBuffer(q, ".");
				appendPQExpBuffer(q, "%s", fmtId(tblinfo[i].attnames[j], force_quotes));
				dumpComment(fout, q->data, tblinfo[i].attoids[j]);
			}
3208

B
Bruce,  
Bruce Momjian 已提交
3209
			/* Dump Table Comments */
3210

B
Bruce,  
Bruce Momjian 已提交
3211 3212 3213
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "TABLE %s", fmtId(tblinfo[i].relname, force_quotes));
			dumpComment(fout, q->data, tblinfo[i].oid);
3214

3215 3216
		}
	}
3217 3218 3219 3220
}

/*
 * dumpIndices:
3221
 *	  write out to fout all the user-define indices
3222
 */
3223
void
3224 3225
dumpIndices(FILE *fout, IndInfo *indinfo, int numIndices,
			TableInfo *tblinfo, int numTables, const char *tablename)
3226
{
3227 3228 3229
	int			i,
				k;
	int			tableInd;
3230
	PQExpBuffer attlist = createPQExpBuffer();
B
Bruce Momjian 已提交
3231 3232 3233
	char	   *classname[INDEX_MAX_KEYS];
	char	   *funcname;		/* the name of the function to comput the
								 * index key from */
3234 3235 3236
	int			indkey,
				indclass;
	int			nclass;
3237

3238
	PQExpBuffer q = createPQExpBuffer(),
B
Hi, all  
Bruce Momjian 已提交
3239 3240
				id1 = createPQExpBuffer(),
				id2 = createPQExpBuffer();
3241
	PGresult   *res;
3242 3243 3244 3245

	for (i = 0; i < numIndices; i++)
	{
		tableInd = findTableByName(tblinfo, numTables,
3246 3247 3248 3249 3250
								   indinfo[i].indrelname);
		if (tableInd < 0)
		{
			fprintf(stderr, "failed sanity check, table %s was not found\n",
					indinfo[i].indrelname);
3251
			exit(1);
3252
		}
3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264

		if (strcmp(indinfo[i].indproc, "0") == 0)
			funcname = NULL;
		else
		{

			/*
			 * the funcname is an oid which we use to find the name of the
			 * pg_proc.  We need to do this because getFuncs() only reads
			 * in the user-defined funcs not all the funcs.  We might not
			 * find what we want by looking in FuncInfo*
			 */
B
Hi, all  
Bruce Momjian 已提交
3265 3266
			resetPQExpBuffer(q);
			appendPQExpBuffer(q,
3267 3268 3269
							  "SELECT proname from pg_proc "
							  "where pg_proc.oid = '%s'::oid",
							  indinfo[i].indproc);
B
Hi, all  
Bruce Momjian 已提交
3270
			res = PQexec(g_conn, q->data);
3271 3272
			if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
			{
B
Bruce Momjian 已提交
3273
				fprintf(stderr, "dumpIndices(): SELECT (funcname) failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286
				exit_nicely(g_conn);
			}
			funcname = strdup(PQgetvalue(res, 0,
										 PQfnumber(res, "proname")));
			PQclear(res);
		}

		/* convert opclass oid(s) into names */
		for (nclass = 0; nclass < INDEX_MAX_KEYS; nclass++)
		{
			indclass = atoi(indinfo[i].indclass[nclass]);
			if (indclass == 0)
				break;
B
Hi, all  
Bruce Momjian 已提交
3287 3288
			resetPQExpBuffer(q);
			appendPQExpBuffer(q,
3289 3290 3291
							  "SELECT opcname from pg_opclass "
							  "where pg_opclass.oid = '%u'::oid",
							  indclass);
B
Hi, all  
Bruce Momjian 已提交
3292
			res = PQexec(g_conn, q->data);
3293 3294
			if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
			{
B
Bruce Momjian 已提交
3295
				fprintf(stderr, "dumpIndices(): SELECT (classname) failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310
				exit_nicely(g_conn);
			}
			classname[nclass] = strdup(PQgetvalue(res, 0,
											 PQfnumber(res, "opcname")));
			PQclear(res);
		}

		if (funcname && nclass != 1)
		{
			fprintf(stderr, "dumpIndices(): Must be exactly one OpClass "
					"for functional index %s\n", indinfo[i].indexrelname);
			exit_nicely(g_conn);
		}

		/* convert attribute numbers into attribute list */
B
Hi, all  
Bruce Momjian 已提交
3311 3312
		resetPQExpBuffer(attlist);
		for (k = 0; k < INDEX_MAX_KEYS; k++)
3313
		{
3314
			char	   *attname;
3315 3316

			indkey = atoi(indinfo[i].indkey[k]);
B
Bruce Momjian 已提交
3317
			if (indkey == InvalidAttrNumber)
3318 3319 3320 3321 3322 3323 3324
				break;
			indkey--;
			if (indkey == ObjectIdAttributeNumber - 1)
				attname = "oid";
			else
				attname = tblinfo[tableInd].attnames[indkey];
			if (funcname)
B
Hi, all  
Bruce Momjian 已提交
3325
				appendPQExpBuffer(attlist, "%s%s",
B
Bruce Momjian 已提交
3326
					 (k == 0) ? "" : ", ", fmtId(attname, force_quotes));
3327 3328 3329 3330 3331
			else
			{
				if (k >= nclass)
				{
					fprintf(stderr, "dumpIndices(): OpClass not found for "
3332
							"attribute '%s' of index '%s'\n",
3333 3334 3335
							attname, indinfo[i].indexrelname);
					exit_nicely(g_conn);
				}
B
Hi, all  
Bruce Momjian 已提交
3336 3337 3338 3339 3340
				resetPQExpBuffer(id1);
				resetPQExpBuffer(id2);
				appendPQExpBuffer(id1, fmtId(attname, force_quotes));
				appendPQExpBuffer(id2, fmtId(classname[k], force_quotes));
				appendPQExpBuffer(attlist, "%s%s %s",
3341
							 (k == 0) ? "" : ", ", id1->data, id2->data);
3342 3343 3344 3345 3346 3347
				free(classname[k]);
			}
		}

		if (!tablename || (!strcmp(indinfo[i].indrelname, tablename)))
		{
B
Bruce Momjian 已提交
3348 3349 3350 3351 3352

			/*
			 * We make the index belong to the owner of its table, which
			 * is not necessarily right but should answer 99% of the time.
			 * Would have to add owner name to IndInfo to do it right.
3353 3354
			 */
			becomeUser(fout, tblinfo[tableInd].usename);
3355

B
Hi, all  
Bruce Momjian 已提交
3356 3357 3358 3359
			resetPQExpBuffer(id1);
			resetPQExpBuffer(id2);
			appendPQExpBuffer(id1, fmtId(indinfo[i].indexrelname, force_quotes));
			appendPQExpBuffer(id2, fmtId(indinfo[i].indrelname, force_quotes));
3360

3361
			if (dropSchema)
B
Bruce Momjian 已提交
3362
			{
B
Hi, all  
Bruce Momjian 已提交
3363 3364 3365
				resetPQExpBuffer(q);
				appendPQExpBuffer(q, "DROP INDEX %s;\n", id1->data);
				fputs(q->data, fout);
B
Bruce Momjian 已提交
3366
			}
3367

3368
			fprintf(fout, "CREATE %s INDEX %s on %s using %s (",
3369
			  (strcmp(indinfo[i].indisunique, "t") == 0) ? "UNIQUE" : "",
B
Hi, all  
Bruce Momjian 已提交
3370 3371
					id1->data,
					id2->data,
3372 3373 3374
					indinfo[i].indamname);
			if (funcname)
			{
3375
				/* need 2 printf's here cuz fmtId has static return area */
3376
				fprintf(fout, " %s", fmtId(funcname, false));
B
Hi, all  
Bruce Momjian 已提交
3377
				fprintf(fout, " (%s) %s );\n", attlist->data, fmtId(classname[0], force_quotes));
3378 3379 3380 3381
				free(funcname);
				free(classname[0]);
			}
			else
B
Hi, all  
Bruce Momjian 已提交
3382
				fprintf(fout, " %s );\n", attlist->data);
B
Bruce,  
Bruce Momjian 已提交
3383 3384 3385 3386 3387 3388

			/* Dump Index Comments */

			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "INDEX %s", id1->data);
			dumpComment(fout, q->data, indinfo[i].indoid);
3389

3390 3391
		}
	}
3392 3393

}
3394

3395
/*
B
Bruce Momjian 已提交
3396
 * dumpTuples
3397 3398 3399 3400 3401
 *	  prints out the tuples in ASCII representation. The output is a valid
 *	  input to COPY FROM stdin.
 *
 *	  We only need to do this for POSTGRES 4.2 databases since the
 *	  COPY TO statment doesn't escape newlines properly. It's been fixed
3402
 *	  in PostgreSQL.
3403 3404 3405 3406
 *
 * the attrmap passed in tells how to map the attributes copied in to the
 * attributes copied out
 */
3407
#ifdef NOT_USED
3408
void
3409
dumpTuples(PGresult *res, FILE *fout, int *attrmap)
3410
{
3411 3412 3413 3414
	int			j,
				k;
	int			m,
				n;
B
Bruce Momjian 已提交
3415
	char	  **outVals = NULL; /* values to copy out */
3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434

	n = PQntuples(res);
	m = PQnfields(res);

	if (m > 0)
	{

		/*
		 * Print out the tuples but only print tuples with at least 1
		 * field.
		 */
		outVals = (char **) malloc(m * sizeof(char *));

		for (j = 0; j < n; j++)
		{
			for (k = 0; k < m; k++)
				outVals[attrmap[k]] = PQgetvalue(res, j, k);
			for (k = 0; k < m; k++)
			{
3435
				char	   *pval = outVals[k];
3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455

				if (k != 0)
					fputc('\t', fout);	/* delimiter for attribute */

				if (pval)
				{
					while (*pval != '\0')
					{
						/* escape tabs, newlines and backslashes */
						if (*pval == '\t' || *pval == '\n' || *pval == '\\')
							fputc('\\', fout);
						fputc(*pval, fout);
						pval++;
					}
				}
			}
			fputc('\n', fout);	/* delimiter for a tuple */
		}
		free(outVals);
	}
3456
}
3457

3458
#endif
3459

3460 3461 3462 3463
/*
 * setMaxOid -
 * find the maximum oid and generate a COPY statement to set it
*/
3464

3465
static void
3466
setMaxOid(FILE *fout)
3467
{
B
Bruce Momjian 已提交
3468
	PGresult   *res;
3469
	Oid			max_oid;
3470 3471 3472 3473 3474

	res = PQexec(g_conn, "CREATE TABLE pgdump_oid (dummy int4)");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
B
Bruce Momjian 已提交
3475
		fprintf(stderr, "Can not create pgdump_oid table.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
3476 3477 3478 3479 3480 3481 3482
		exit_nicely(g_conn);
	}
	PQclear(res);
	res = PQexec(g_conn, "INSERT INTO pgdump_oid VALUES (0)");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
B
Bruce Momjian 已提交
3483
		fprintf(stderr, "Can not insert into pgdump_oid table.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496
		exit_nicely(g_conn);
	}
	max_oid = atol(PQoidStatus(res));
	if (max_oid == 0)
	{
		fprintf(stderr, "Invalid max id in setMaxOid\n");
		exit_nicely(g_conn);
	}
	PQclear(res);
	res = PQexec(g_conn, "DROP TABLE pgdump_oid;");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
B
Bruce Momjian 已提交
3497
		fprintf(stderr, "Can not drop pgdump_oid table.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
3498 3499 3500 3501
		exit_nicely(g_conn);
	}
	PQclear(res);
	if (g_verbose)
3502
		fprintf(stderr, "%s maximum system oid is %u %s\n",
3503 3504 3505 3506 3507 3508 3509
				g_comment_start, max_oid, g_comment_end);
	fprintf(fout, "CREATE TABLE pgdump_oid (dummy int4);\n");
	fprintf(fout, "COPY pgdump_oid WITH OIDS FROM stdin;\n");
	fprintf(fout, "%-d\t0\n", max_oid);
	fprintf(fout, "\\.\n");
	fprintf(fout, "DROP TABLE pgdump_oid;\n");
}
3510 3511 3512

/*
 * findLastBuiltInOid -
3513
 * find the last built in oid
3514
 * we do this by looking up the oid of 'template1' in pg_database,
3515
 * this is probably not foolproof but comes close
3516 3517
*/

3518
static int
3519
findLastBuiltinOid(void)
3520
{
B
Bruce Momjian 已提交
3521
	PGresult   *res;
3522 3523
	int			ntups;
	int			last_oid;
3524 3525 3526 3527 3528 3529

	res = PQexec(g_conn,
			  "SELECT oid from pg_database where datname = 'template1'");
	if (res == NULL ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
3530 3531
		fprintf(stderr, "pg_dump error in finding the template1 database.");
		fprintf(stderr, "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
3532 3533 3534
		exit_nicely(g_conn);
	}
	ntups = PQntuples(res);
3535
	if (ntups < 1)
3536
	{
3537 3538
		fprintf(stderr, "pg_dump: couldn't find the template1 database.\n");
		fprintf(stderr, "There is no 'template1' entry in the 'pg_database' table.\n");
3539 3540 3541 3542
		exit_nicely(g_conn);
	}
	if (ntups > 1)
	{
3543 3544
		fprintf(stderr, "pg_dump: found more than one template1 database.\n");
		fprintf(stderr, "There is more than one 'template1' entry in the 'pg_database' table\n");
3545 3546 3547 3548 3549
		exit_nicely(g_conn);
	}
	last_oid = atoi(PQgetvalue(res, 0, PQfnumber(res, "oid")));
	PQclear(res);
	return last_oid;
3550 3551 3552 3553 3554
}


/*
 * checkForQuote:
3555
 *	  checks a string for quote characters and quotes them
3556
 */
3557
static char *
3558
checkForQuote(const char *s)
3559
{
B
Bruce Momjian 已提交
3560
	char	   *r;
3561
	char		c;
B
Bruce Momjian 已提交
3562
	char	   *result;
3563

3564
	int			j = 0;
3565

3566
	r = malloc(strlen(s) * 3 + 1);		/* definitely long enough */
3567

3568 3569
	while ((c = *s) != '\0')
	{
3570

3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581
		if (c == '\'')
		{
			r[j++] = '\'';		/* quote the single quotes */
		}
		r[j++] = c;
		s++;
	}
	r[j] = '\0';

	result = strdup(r);
	free(r);
3582

3583
	return result;
3584 3585

}
3586 3587


3588
static void
3589
dumpSequence(FILE *fout, TableInfo tbinfo)
3590
{
3591
	PGresult   *res;
B
Bruce Momjian 已提交
3592
	int4		last,
3593 3594 3595 3596
				incby,
				maxv,
				minv,
				cache;
B
Bruce Momjian 已提交
3597
	char		cycled,
B
Bruce Momjian 已提交
3598
				called;
3599 3600
	const char *t;
	PQExpBuffer query = createPQExpBuffer();
3601

B
Hi, all  
Bruce Momjian 已提交
3602
	appendPQExpBuffer(query,
3603
			"SELECT sequence_name, last_value, increment_by, max_value, "
3604 3605
				  "min_value, cache_value, is_cycled, is_called from %s",
					  fmtId(tbinfo.relname, force_quotes));
3606

B
Hi, all  
Bruce Momjian 已提交
3607
	res = PQexec(g_conn, query->data);
3608 3609
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
3610
		fprintf(stderr, "dumpSequence(%s): SELECT failed.  Explanation from backend: '%s'.\n", tbinfo.relname, PQerrorMessage(g_conn));
3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641
		exit_nicely(g_conn);
	}

	if (PQntuples(res) != 1)
	{
		fprintf(stderr, "dumpSequence(%s): %d (!= 1) tuples returned by SELECT\n",
				tbinfo.relname, PQntuples(res));
		exit_nicely(g_conn);
	}

	if (strcmp(PQgetvalue(res, 0, 0), tbinfo.relname) != 0)
	{
		fprintf(stderr, "dumpSequence(%s): different sequence name "
				"returned by SELECT: %s\n",
				tbinfo.relname, PQgetvalue(res, 0, 0));
		exit_nicely(g_conn);
	}


	last = atoi(PQgetvalue(res, 0, 1));
	incby = atoi(PQgetvalue(res, 0, 2));
	maxv = atoi(PQgetvalue(res, 0, 3));
	minv = atoi(PQgetvalue(res, 0, 4));
	cache = atoi(PQgetvalue(res, 0, 5));
	t = PQgetvalue(res, 0, 6);
	cycled = *t;
	t = PQgetvalue(res, 0, 7);
	called = *t;

	PQclear(res);

3642
	if (dropSchema)
B
Bruce Momjian 已提交
3643
	{
B
Hi, all  
Bruce Momjian 已提交
3644 3645 3646
		resetPQExpBuffer(query);
		appendPQExpBuffer(query, "DROP SEQUENCE %s;\n", fmtId(tbinfo.relname, force_quotes));
		fputs(query->data, fout);
B
Bruce Momjian 已提交
3647
	}
3648

B
Hi, all  
Bruce Momjian 已提交
3649 3650
	resetPQExpBuffer(query);
	appendPQExpBuffer(query,
3651 3652
				  "CREATE SEQUENCE %s start %d increment %d maxvalue %d "
					  "minvalue %d  cache %d %s;\n",
B
Bruce Momjian 已提交
3653
	 fmtId(tbinfo.relname, force_quotes), last, incby, maxv, minv, cache,
3654
					  (cycled == 't') ? "cycle" : "");
3655

B
Hi, all  
Bruce Momjian 已提交
3656
	fputs(query->data, fout);
3657

B
Bruce,  
Bruce Momjian 已提交
3658 3659 3660 3661 3662 3663
	/* Dump Sequence Comments */

	resetPQExpBuffer(query);
	appendPQExpBuffer(query, "SEQUENCE %s", fmtId(tbinfo.relname, force_quotes));
	dumpComment(fout, query->data, tbinfo.oid);

3664 3665 3666
	if (called == 'f')
		return;					/* nothing to do more */

B
Hi, all  
Bruce Momjian 已提交
3667 3668 3669
	resetPQExpBuffer(query);
	appendPQExpBuffer(query, "SELECT nextval ('%s');\n", fmtId(tbinfo.relname, force_quotes));
	fputs(query->data, fout);
3670 3671

}
V
Vadim B. Mikheev 已提交
3672 3673


3674 3675 3676
static void
dumpTriggers(FILE *fout, const char *tablename,
			 TableInfo *tblinfo, int numTables)
V
Vadim B. Mikheev 已提交
3677
{
3678 3679 3680
	int			i,
				j;

V
Vadim B. Mikheev 已提交
3681 3682 3683
	if (g_verbose)
		fprintf(stderr, "%s dumping out triggers %s\n",
				g_comment_start, g_comment_end);
3684

V
Vadim B. Mikheev 已提交
3685 3686 3687 3688 3689 3690
	for (i = 0; i < numTables; i++)
	{
		if (tablename && strcmp(tblinfo[i].relname, tablename))
			continue;
		for (j = 0; j < tblinfo[i].ntrig; j++)
		{
3691
			becomeUser(fout, tblinfo[i].usename);
V
Vadim B. Mikheev 已提交
3692
			fputs(tblinfo[i].triggers[j], fout);
B
Bruce,  
Bruce Momjian 已提交
3693
			dumpComment(fout, tblinfo[i].trcomments[j], tblinfo[i].troids[j]);
V
Vadim B. Mikheev 已提交
3694 3695 3696
		}
	}
}
3697 3698


3699 3700
static void
dumpRules(FILE *fout, const char *tablename,
B
Bruce Momjian 已提交
3701
		  TableInfo *tblinfo, int numTables)
3702
{
B
Bruce Momjian 已提交
3703 3704 3705 3706
	PGresult   *res;
	int			nrules;
	int			i,
				t;
3707
	PQExpBuffer query = createPQExpBuffer();
3708

B
Bruce Momjian 已提交
3709
	int			i_definition;
3710 3711
	int			i_oid;
	int			i_rulename;
3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727

	if (g_verbose)
		fprintf(stderr, "%s dumping out rules %s\n",
				g_comment_start, g_comment_end);

	/*
	 * For each table we dump
	 */
	for (t = 0; t < numTables; t++)
	{
		if (tablename && strcmp(tblinfo[t].relname, tablename))
			continue;

		/*
		 * Get all rules defined for this table
		 */
B
Hi, all  
Bruce Momjian 已提交
3728 3729
		resetPQExpBuffer(query);
		appendPQExpBuffer(query, "SELECT pg_get_ruledef(pg_rewrite.rulename) "
3730 3731 3732 3733 3734
						  "AS definition, pg_rewrite.oid, pg_rewrite.rulename FROM pg_rewrite, pg_class "
						  "WHERE pg_class.relname = '%s' "
						  "AND pg_rewrite.ev_class = pg_class.oid "
						  "ORDER BY pg_rewrite.oid",
						  tblinfo[t].relname);
B
Hi, all  
Bruce Momjian 已提交
3735
		res = PQexec(g_conn, query->data);
3736 3737 3738
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
B
Bruce Momjian 已提交
3739 3740
			fprintf(stderr, "dumpRules(): SELECT failed for table %s.  Explanation from backend: '%s'.\n",
					tblinfo[t].relname, PQerrorMessage(g_conn));
3741 3742 3743 3744 3745
			exit_nicely(g_conn);
		}

		nrules = PQntuples(res);
		i_definition = PQfnumber(res, "definition");
B
Bruce,  
Bruce Momjian 已提交
3746 3747
		i_oid = PQfnumber(res, "oid");
		i_rulename = PQfnumber(res, "rulename");
3748 3749 3750 3751

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

3753 3754 3755
		for (i = 0; i < nrules; i++)
		{

3756 3757
			fprintf(fout, "%s\n", PQgetvalue(res, i, i_definition));

B
Bruce,  
Bruce Momjian 已提交
3758 3759 3760 3761 3762
			/* Dump rule comments */

			resetPQExpBuffer(query);
			appendPQExpBuffer(query, "RULE %s", fmtId(PQgetvalue(res, i, i_rulename), force_quotes));
			dumpComment(fout, query->data, PQgetvalue(res, i, i_oid));
3763

B
Bruce,  
Bruce Momjian 已提交
3764 3765
		}

3766 3767 3768 3769 3770
		PQclear(res);
	}
}


3771 3772 3773 3774 3775 3776
/* Issue a psql \connect command to become the specified user.
 * We want to do this only if we are dumping ACLs,
 * and only if the new username is different from the last one
 * (to avoid the overhead of useless backend launches).
 */

3777 3778
static void
becomeUser(FILE *fout, const char *username)
3779 3780 3781
{
	static const char *lastusername = "";

3782
	if (aclsSkip)
3783 3784 3785 3786 3787 3788 3789 3790 3791
		return;

	if (strcmp(lastusername, username) == 0)
		return;

	fprintf(fout, "\\connect - %s\n", username);

	lastusername = username;
}