pg_dump.c 79.6 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 20 21 22 23
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
24
 *	  $Header: /cvsroot/pgsql/src/bin/pg_dump/pg_dump.c,v 1.106 1999/05/13 02:35:44 momjian Exp $
25
 *
26
 * Modifications - 6/10/96 - dave@bensoft.com - version 1.13.dhb
27
 *
28 29 30 31
 *	 Applied 'insert string' patch from "Marc G. Fournier" <scrappy@ki.net>
 *	 Added '-t table' option
 *	 Added '-a' option
 *	 Added '-da' option
32
 *
33 34
 * Modifications - 6/12/96 - dave@bensoft.com - version 1.13.dhb.2
 *
35 36 37
 *	 - Fixed dumpTable output to output lengths for char and varchar types!
 *	 - Added single. quote to twin single quote expansion for 'insert' string
 *	   mode.
38
 *
39 40
 * Modifications - 7/26/96 - asussman@vidya.com
 *
41
 *	 - Fixed ouput lengths for char and varchar type where the length is variable (-1)
42
 *
43 44
 * Modifications - 6/1/97 - igor@sba.miami.edu
 * - Added functions to free allocated memory used for retrieving
45 46
 *	 indices,tables,inheritance,types,functions and aggregates.
 *	 No more leaks reported by Purify.
47 48 49
 *
 *
 * Modifications - 1/26/98 - pjlobo@euitt.upm.es
50
 *		 - Added support for password authentication
51 52 53 54
 *-------------------------------------------------------------------------
 */

#include <stdlib.h>
55
#include <unistd.h>				/* for getopt() */
56 57
#include <stdio.h>
#include <string.h>
58
#include <ctype.h>
B
Bruce Momjian 已提交
59
#include <sys/param.h>				/* for MAXHOSTNAMELEN on most */
B
Bruce Momjian 已提交
60
#ifdef solaris_sparc
61
#include <netdb.h>				/* for MAXHOSTNAMELEN on some */
62 63 64
#endif

#include "postgres.h"
65
#include "access/htup.h"
66
#include "catalog/pg_type.h"
67
#include "catalog/pg_language.h"
68
#include "catalog/pg_index.h"
V
Vadim B. Mikheev 已提交
69
#include "catalog/pg_trigger.h"
70
#include "libpq-fe.h"
71
#ifndef HAVE_STRDUP
72 73
#include "strdup.h"
#endif
74

75 76 77 78
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif

79 80 81 82
#ifdef __CYGWIN32__
#include <getopt.h>
#endif

83 84
#include "pg_dump.h"

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

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

B
Bruce Momjian 已提交
103
extern char	*optarg;
104
extern int	optind,
B
Bruce Momjian 已提交
105
		opterr;
106 107

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

B
Bruce Momjian 已提交
114 115 116 117 118 119
bool		force_quotes;			/* User wants to suppress double-quotes */
int		dumpData;			/* dump data using proper insert strings */
int		attrNames;			/* put attr names into insert strings */
int		schemaOnly;
int		dataOnly;
int		aclsOption;
120
bool		drop_schema;
121

B
Bruce Momjian 已提交
122
char		g_opaque_type[10];		/* name for the opaque type */
123 124

/* placeholders for the delimiters for comments */
125 126
char		g_comment_start[10];
char		g_comment_end[10];
127 128 129


static void
130
usage(const char *progname)
131
{
132
	fprintf(stderr,
133
			"usage:  %s [options] dbname\n", progname);
134
	fprintf(stderr,
135
			"\t -a          \t\t dump out only the data, no schema\n");
136 137
	fprintf(stderr,
			"\t -c          \t\t clean(drop) schema prior to create\n");
138
	fprintf(stderr,
139
			"\t -d          \t\t dump data as proper insert strings\n");
140
	fprintf(stderr,
141 142
			"\t -D          \t\t dump data as inserts"
							" with attribute names\n");
143
	fprintf(stderr,
144
			"\t -f filename \t\t script output filename\n");
145
	fprintf(stderr,
146
			"\t -h hostname \t\t server host name\n");
147 148
	fprintf(stderr,
			"\t -n          \t\t suppress most quotes around identifiers\n");
149 150
	fprintf(stderr,
			"\t -N          \t\t enable most quotes around identifiers\n");
151
	fprintf(stderr,
152
			"\t -o          \t\t dump object id's (oids)\n");
153
	fprintf(stderr,
154
			"\t -p port     \t\t server port number\n");
155
	fprintf(stderr,
156
			"\t -s          \t\t dump out only the schema, no data\n");
157 158
	fprintf(stderr,
			"\t -t table    \t\t dump for this table only\n");
159 160
	fprintf(stderr,
			"\t -u          \t\t use password authentication\n");
161
	fprintf(stderr,
162
			"\t -v          \t\t verbose\n");
163 164 165 166 167 168 169 170
	fprintf(stderr,
			"\t -z          \t\t dump ACLs (grant/revoke)\n");
	fprintf(stderr,
			"\nIf dbname is not supplied, then the DATABASE environment "
			"variable value is used.\n");
	fprintf(stderr, "\n");

	exit(1);
171 172
}

173
static void
174
exit_nicely(PGconn *conn)
175
{
176 177
	PQfinish(conn);
	exit(1);
178 179 180
}


M
Marc G. Fournier 已提交
181 182
/*
 * isViewRule
183
 *				Determine if the relation is a VIEW
M
Marc G. Fournier 已提交
184 185
 *
 */
186
static bool
M
Marc G. Fournier 已提交
187 188
isViewRule(char *relname)
{
B
Bruce Momjian 已提交
189 190
	PGresult	*res;
	int		ntups;
191
	char		query[MAXQUERYLEN];
192 193 194 195 196 197 198 199 200 201 202 203

	res = PQexec(g_conn, "begin");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, "BEGIN command failed\n");
		exit_nicely(g_conn);
	}
	PQclear(res);

	sprintf(query, "select relname from pg_class, pg_rewrite "
			"where pg_class.oid = ev_class "
204
			"and pg_rewrite.ev_type = '1' "
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
			"and rulename = '_RET%s'", relname);

	res = PQexec(g_conn, query);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, "isViewRule(): SELECT failed\n");
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	PQclear(res);
	res = PQexec(g_conn, "end");
	PQclear(res);
	return ntups > 0 ? TRUE : FALSE;
M
Marc G. Fournier 已提交
221
}
222

223 224 225 226
#define COPYBUFSIZ		8192


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

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

	if (oids)
	{
238
		fprintf(fout, "COPY %s WITH OIDS FROM stdin;\n",
239
				fmtId(classname, force_quotes));
240
		sprintf(query, "COPY %s WITH OIDS TO stdout;\n",
241
				fmtId(classname, force_quotes));
242 243 244
	}
	else
	{
245 246
		fprintf(fout, "COPY %s FROM stdin;\n", fmtId(classname, force_quotes));
		sprintf(query, "COPY %s TO stdout;\n", fmtId(classname, force_quotes));
247 248
	}
	res = PQexec(g_conn, query);
249 250
	if (!res ||
		PQresultStatus(res) == PGRES_FATAL_ERROR)
251
	{
252
		fprintf(stderr, "SQL query to dump the contents of Table '%s' "
253 254 255 256 257 258 259 260 261
				"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)
		{
262
			fprintf(stderr, "SQL query to dump the contents of Table '%s' "
263 264 265 266 267 268 269 270 271 272 273
					"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)
			{
274
				ret = PQgetline(g_conn, copybuf, COPYBUFSIZ);
275 276 277 278 279 280 281 282 283 284 285 286

				if (copybuf[0] == '\\' &&
					copybuf[1] == '.' &&
					copybuf[2] == '\0')
				{
					copydone = true;	/* don't print this... */
				}
				else
				{
					fputs(copybuf, fout);
					switch (ret)
					{
287 288 289 290 291 292 293 294
						case EOF:
							copydone = true;
							/* FALLTHROUGH */
						case 0:
							fputc('\n', fout);
							break;
						case 1:
							break;
295 296 297 298 299
					}
				}
			}
			fprintf(fout, "\\.\n");
		}
300
		ret = PQendcopy(g_conn);
301 302
		if (ret != 0)
		{
303
			fprintf(stderr, "SQL query to dump the contents of Table '%s' "
304 305 306 307 308 309 310 311 312 313 314 315
					"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);
			if (res)
				PQclear(res);
			exit_nicely(g_conn);
		}
		if (res)
			PQclear(res);
	}
316 317 318 319 320
}



static void
321
dumpClasses_dumpData(FILE *fout, const char *classname,
322 323
					 const TableInfo tblinfo, bool oids)
{
B
Bruce Momjian 已提交
324
	PGresult	*res;
325
	char		q[MAXQUERYLEN];
326 327 328 329
	int			tuple;
	int			field;
	char	   *expsrc;
	char	   *expdest;
330

331 332
	sprintf(q, "SELECT * FROM %s", fmtId(classname, force_quotes));
	res = PQexec(g_conn, q);
333 334 335 336 337 338
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, "dumpClasses(): command failed\n");
		exit_nicely(g_conn);
	}
339
	for (tuple = 0; tuple < PQntuples(res); tuple++)
340
	{
341
		fprintf(fout, "INSERT INTO %s ", fmtId(classname, force_quotes));
342 343 344
		if (attrNames)
		{
			sprintf(q, "(");
345
			for (field = 0; field < PQnfields(res); field++)
346
			{
347 348 349
				if (field > 0)
					strcat(q, ",");
				strcat(q, fmtId(PQfname(res, field), force_quotes));
350
			}
351 352
			strcat(q, ") ");
			fprintf(fout, "%s", q);
353 354
		}
		fprintf(fout, "values (");
355
		for (field = 0; field < PQnfields(res); field++)
356
		{
357 358
			if (field > 0)
				fprintf(fout, ",");
359 360 361 362 363 364
			if (PQgetisnull(res, tuple, field))
				fprintf(fout, "NULL");
			else
			{
				switch (PQftype(res, field))
				{
365 366 367 368 369
					case INT2OID:
					case INT4OID:
					case OIDOID:		/* int types */
					case FLOAT4OID:
					case FLOAT8OID:		/* float types */
370
						/* These types are printed without quotes */
371 372 373 374
						fprintf(fout, "%s",
								PQgetvalue(res, tuple, field));
						break;
					default:
375 376 377 378 379 380 381 382
						/* All other types are printed as string literals,
						 * with appropriate escaping of special characters.
						 * Quote mark ' goes to '' per SQL standard,
						 * other stuff goes to \ sequences.
						 */
						expsrc = PQgetvalue(res, tuple, field);
						expdest = q;
						for (; *expsrc; expsrc++)
383
						{
384 385
							char ch = *expsrc;
							if (ch == '\\' || ch == '\'')
386
							{
387 388
								*expdest++ = ch; /* double it */
								*expdest++ = ch;
389
							}
390 391 392 393 394 395 396 397 398 399
							else if (ch < '\040')
							{
								/* generate octal escape for control chars */
								*expdest++ = '\\';
								*expdest++ = ((ch >> 6) & 3) + '0';
								*expdest++ = ((ch >> 3) & 7) + '0';
								*expdest++ = (ch & 7) + '0';
							}
							else
								*expdest++ = ch;
400
						}
401 402
						*expdest = '\0';
						fprintf(fout, "'%s'", q);
403
						break;
404 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 429 430 431 432 433

	if (onlytable == NULL)
		all_only = "all";
	else
		all_only = "one";

	if (g_verbose)
		fprintf(stderr, "%s dumping out the contents of %s of %d tables %s\n",
				g_comment_start, all_only, numTables, g_comment_end);
434

V
Vadim B. Mikheev 已提交
435 436 437 438 439 440 441 442 443 444
	/* 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)
445
					fprintf(stderr, "%s dumping out schema of sequence '%s' %s\n",
446
					 g_comment_start, tblinfo[i].relname, g_comment_end);
447
				becomeUser(fout, tblinfo[i].usename);
V
Vadim B. Mikheev 已提交
448 449 450 451
				dumpSequence(fout, tblinfo[i]);
			}
		}
	}
452 453 454

	for (i = 0; i < numTables; i++)
	{
455
		const char *classname = tblinfo[i].relname;
456 457 458 459

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

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

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

470 471
			becomeUser(fout, tblinfo[i].usename);

472 473 474 475
			if (!dumpData)
				dumpClasses_nodumpData(fout, classname, oids);
			else
				dumpClasses_dumpData(fout, classname, tblinfo[i], oids);
476
		}
477
	}
478 479 480
}


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

#ifdef HAVE_TERMIOS_H
B
Bruce Momjian 已提交
488 489
	struct termios	t_orig,
			t;
490 491 492
#endif

	printf("Username: ");
493
	fgets(username, 100, stdin);
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
	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';

	printf("Password: ");
#ifdef HAVE_TERMIOS_H
	tcgetattr(0, &t);
	t_orig = t;
	t.c_lflag &= ~ECHO;
	tcsetattr(0, TCSADRAIN, &t);
#endif
513
	fgets(password, 100, stdin);
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
#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';

	printf("\n\n");
}

533

534
int
535
main(int argc, char **argv)
536
{
B
Bruce Momjian 已提交
537 538 539 540 541 542 543 544 545 546
	int		c;
	const char	*progname;
	const char	*filename = NULL;
	const char	*dbname = NULL;
	const char	*pghost = NULL;
	const char	*pgport = NULL;
	char		*tablename = NULL;
	int		oids = 0;
	TableInfo	*tblinfo;
	int		numTables;
547 548
	char		connect_string[512] = "";
	char		tmp_string[128];
549 550
	char		username[100];
	char		password[100];
B
Bruce Momjian 已提交
551
	int		use_password = 0;
552 553

	g_verbose = false;
554
	force_quotes = true;
555
	drop_schema = false;
556 557 558 559 560

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

561
	dataOnly = schemaOnly = dumpData = attrNames = 0;
562 563 564

	progname = *argv;

565
	while ((c = getopt(argc, argv, "acdDf:h:nNop:st:vzu")) != EOF)
566 567 568
	{
		switch (c)
		{
569 570 571
			case 'a':			/* Dump data only */
				dataOnly = 1;
				break;
572 573 574
			case 'c':			/* clean (i.e., drop) schema prior to create */
				drop_schema = true;
				break;
575 576 577 578 579 580 581 582
			case 'd':			/* dump data as proper insert strings */
				dumpData = 1;
				break;
			case 'D':			/* dump data as proper insert strings with
								 * attr names */
				dumpData = 1;
				attrNames = 1;
				break;
583 584 585
			case 'f':			/* output file name */
				filename = optarg;
				break;
B
Bruce Momjian 已提交
586
			case 'h':			/* server host */
587 588
				pghost = optarg;
				break;
589
			case 'n':			/* Do not force double-quotes on identifiers */
590
				force_quotes = false;
591
				break;
592
			case 'N':			/* Force double-quotes on identifiers */
593
				force_quotes = true;
594
				break;
595 596 597
			case 'o':			/* Dump oids */
				oids = 1;
				break;
598 599 600
			case 'p':			/* server port */
				pgport = optarg;
				break;
601
			case 's':			/* dump schema only */
602 603 604
				schemaOnly = 1;
				break;
			case 't':			/* Dump data for this table only */
605
				{
606
					int			i;
607 608

					tablename = strdup(optarg);
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
					/* quoted string? Then strip quotes and preserve case... */
					if (tablename[0] == '"')
					{
						strcpy(tablename, &tablename[1]);
						if (*(tablename+strlen(tablename)-1) == '"')
							*(tablename+strlen(tablename)-1) = '\0';
					}
					/* otherwise, convert table name to lowercase... */
					else
					{
						for (i = 0; tablename[i]; i++)
							if (isascii((unsigned char) tablename[i]) &&
								isupper(tablename[i]))
								tablename[i] = tolower(tablename[i]);
					}
624
				}
625
				break;
626 627
			case 'v':			/* verbose */
				g_verbose = true;
628
				break;
629 630
			case 'z':			/* Dump ACLs and table ownership info */
				aclsOption = 1;
631
				break;
632 633 634
			case 'u':
				use_password = 1;
				break;
635 636 637
			default:
				usage(progname);
				break;
638 639 640 641 642 643 644 645
		}
	}

	/* open the output file */
	if (filename == NULL)
		g_fout = stdout;
	else
	{
646
#ifndef __CYGWIN32__
647
		g_fout = fopen(filename, "w");
648 649 650
#else
		g_fout = fopen(filename, "wb");
#endif
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
		if (g_fout == NULL)
		{
			fprintf(stderr,
				 "%s: could not open output file named %s for writing\n",
					progname, filename);
			exit(2);
		}
	}

	/* find database */
	if (!(dbname = argv[optind]) &&
		!(dbname = getenv("DATABASE")))
	{
		fprintf(stderr, "%s: no database name specified\n", progname);
		exit(2);
	}

668 669 670 671 672
	/* g_conn = PQsetdb(pghost, pgport, NULL, NULL, dbname); */
	if (pghost != NULL)
	{
		sprintf(tmp_string, "host=%s ", pghost);
		strcat(connect_string, tmp_string);
673
	}
674 675 676 677
	if (pgport != NULL)
	{
		sprintf(tmp_string, "port=%s ", pgport);
		strcat(connect_string, tmp_string);
678
	}
679 680 681 682
	if (dbname != NULL)
	{
		sprintf(tmp_string, "dbname=%s ", dbname);
		strcat(connect_string, tmp_string);
683
	}
684 685 686 687 688 689 690 691
	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);
692 693
		MemSet(tmp_string, 0, sizeof(tmp_string));
		MemSet(password, 0, sizeof(password));
694 695
	}
	g_conn = PQconnectdb(connect_string);
696
	MemSet(connect_string, 0, sizeof(connect_string));
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
	/* 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);
	}

	g_last_builtin_oid = findLastBuiltinOid();

	if (oids)
		setMaxOid(g_fout);
	if (!dataOnly)
	{
		if (g_verbose)
712
			fprintf(stderr, "%s last builtin oid is %u %s\n",
713
					g_comment_start, g_last_builtin_oid, g_comment_end);
714
		tblinfo = dumpSchema(g_fout, &numTables, tablename, aclsOption);
715 716
	}
	else
717
		tblinfo = dumpSchema(NULL, &numTables, tablename, aclsOption);
718 719 720 721

	if (!schemaOnly)
		dumpClasses(tblinfo, numTables, g_fout, tablename, oids);

722 723
	if (!dataOnly)				/* dump indexes and triggers at the end
								 * for performance */
V
Vadim B. Mikheev 已提交
724 725 726
	{
		dumpSchemaIdx(g_fout, tablename, tblinfo, numTables);
		dumpTriggers(g_fout, tablename, tblinfo, numTables);
727
		dumpRules(g_fout, tablename, tblinfo, numTables);
V
Vadim B. Mikheev 已提交
728
	}
729 730 731 732 733 734

	fflush(g_fout);
	fclose(g_fout);
	clearTableInfo(tblinfo, numTables);
	PQfinish(g_conn);
	exit(0);
735 736 737
}

/*
738 739
 * getTypes:
 *	  read all base types in the system catalogs and return them in the
740 741
 * TypeInfo* structure
 *
742
 *	numTypes is set to the number of types read in
743 744
 *
 */
745
TypeInfo   *
746 747
getTypes(int *numTypes)
{
B
Bruce Momjian 已提交
748
	PGresult		*res;
749 750
	int			ntups;
	int			i;
B
Bruce Momjian 已提交
751 752
	char			query[MAXQUERYLEN];
	TypeInfo		*tinfo;
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768

	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;
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862

	res = PQexec(g_conn, "begin");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, "BEGIN command failed\n");
		exit_nicely(g_conn);
	}
	PQclear(res);

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

	sprintf(query, "SELECT pg_type.oid, typowner,typname, typlen, typprtlen, "
		  "typinput, typoutput, typreceive, typsend, typelem, typdelim, "
		  "typdefault, typrelid,typbyval, usename from pg_type, pg_user "
			"where typowner = usesysid");

	res = PQexec(g_conn, query);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, "getTypes(): SELECT failed\n");
		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);

	res = PQexec(g_conn, "end");
	PQclear(res);

	return tinfo;
863 864 865 866
}

/*
 * getOperators:
867
 *	  read all operators in the system catalogs and return them in the
868 869
 * OprInfo* structure
 *
870 871
 *	numOprs is set to the number of operators read in
 *
872 873
 *
 */
874
OprInfo    *
875 876
getOperators(int *numOprs)
{
B
Bruce Momjian 已提交
877
	PGresult		*res;
878 879
	int			ntups;
	int			i;
B
Bruce Momjian 已提交
880
	char			query[MAXQUERYLEN];
881

B
Bruce Momjian 已提交
882
	OprInfo			*oprinfo;
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897

	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;
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968

	/*
	 * find all operators, including builtin operators, filter out
	 * system-defined operators at dump-out time
	 */
	res = PQexec(g_conn, "begin");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, "BEGIN command failed\n");
		exit_nicely(g_conn);
	}
	PQclear(res);

	sprintf(query, "SELECT pg_operator.oid, oprname, oprkind, oprcode, "
			"oprleft, oprright, oprcom, oprnegate, oprrest, oprjoin, "
			"oprcanhash, oprlsortop, oprrsortop, usename "
			"from pg_operator, pg_user "
			"where oprowner = usesysid");

	res = PQexec(g_conn, query);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, "getOperators(): SELECT failed\n");
		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);
	res = PQexec(g_conn, "end");
	PQclear(res);

	return oprinfo;
969 970
}

971
void
972
clearTypeInfo(TypeInfo *tp, int numTypes)
973
{
974
	int			i;
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

	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);
1008 1009 1010
}

void
1011
clearFuncInfo(FuncInfo *fun, int numFuncs)
1012
{
1013 1014
	int			i,
				a;
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036

	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);
		for (a = 0; a < 8; ++a)
			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);
1037 1038
}

1039
static void
1040
clearTableInfo(TableInfo *tblinfo, int numTables)
1041
{
1042 1043
	int			i,
				j;
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068

	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++)
		{
			if (tblinfo[i].attnames[j])
				free(tblinfo[i].attnames[j]);
			if (tblinfo[i].typnames[j])
				free(tblinfo[i].typnames[j]);
		}
1069 1070
		if (tblinfo[i].atttypmod)
			free((int *) tblinfo[i].atttypmod);
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
		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);

	}
	free(tblinfo);
1082 1083
}

1084
void
1085
clearInhInfo(InhInfo *inh, int numInherits)
1086
{
1087
	int			i;
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098

	if (!inh)
		return;
	for (i = 0; i < numInherits; ++i)
	{
		if (inh[i].inhrel)
			free(inh[i].inhrel);
		if (inh[i].inhparent)
			free(inh[i].inhparent);
	}
	free(inh);
1099 1100 1101
}

void
1102
clearOprInfo(OprInfo *opr, int numOprs)
1103
{
1104
	int			i;
1105 1106 1107 1108 1109 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

	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);
1140 1141 1142
}

void
1143
clearIndInfo(IndInfo *ind, int numIndices)
1144
{
1145 1146
	int			i,
				a;
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170

	if (!ind)
		return;
	for (i = 0; i < numIndices; ++i)
	{
		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);
1171 1172 1173
}

void
B
Bruce Momjian 已提交
1174
clearAggInfo(AggInfo *agginfo, int numArgs)
1175
{
1176
	int			i;
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205

	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);
1206
}
1207 1208 1209

/*
 * getAggregates:
1210
 *	  read all the user-defined aggregates in the system catalogs and
1211 1212
 * return them in the AggInfo* structure
 *
1213 1214
 * numAggs is set to the number of aggregates read in
 *
1215 1216
 *
 */
1217
AggInfo    *
1218 1219
getAggregates(int *numAggs)
{
B
Bruce Momjian 已提交
1220
	PGresult		*res;
1221 1222
	int			ntups;
	int			i;
B
Bruce Momjian 已提交
1223 1224
	char			query[MAXQUERYLEN];
	AggInfo			*agginfo;
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236

	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;
1237 1238 1239 1240 1241 1242 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 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299

	/* find all user-defined aggregates */

	res = PQexec(g_conn, "begin");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, "BEGIN command failed\n");
		exit_nicely(g_conn);
	}
	PQclear(res);

	sprintf(query,
			"SELECT pg_aggregate.oid, aggname, aggtransfn1, aggtransfn2, "
			"aggfinalfn, aggtranstype1, aggbasetype, aggtranstype2, "
		  "agginitval1, agginitval2, usename from pg_aggregate, pg_user "
			"where aggowner = usesysid");

	res = PQexec(g_conn, query);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, "getAggregates(): SELECT failed\n");
		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);

	res = PQexec(g_conn, "end");
	PQclear(res);
	return agginfo;
1300 1301 1302 1303
}

/*
 * getFuncs:
1304
 *	  read all the user-defined functions in the system catalogs and
1305 1306
 * return them in the FuncInfo* structure
 *
1307 1308
 * numFuncs is set to the number of functions read in
 *
1309 1310
 *
 */
1311
FuncInfo   *
1312 1313
getFuncs(int *numFuncs)
{
B
Bruce Momjian 已提交
1314
	PGresult		*res;
1315 1316
	int			ntups;
	int			i;
B
Bruce Momjian 已提交
1317 1318
	char			query[MAXQUERYLEN];
	FuncInfo		*finfo;
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329

	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;
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345

	/* find all user-defined funcs */

	res = PQexec(g_conn, "begin");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, "BEGIN command failed\n");
		exit_nicely(g_conn);
	}
	PQclear(res);

	sprintf(query,
			"SELECT pg_proc.oid, proname, prolang, pronargs, prorettype, "
			"proretset, proargtypes, prosrc, probin, usename "
			"from pg_proc, pg_user "
1346
			"where pg_proc.oid > '%u'::oid and proowner = usesysid",
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
			g_last_builtin_oid);

	res = PQexec(g_conn, query);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, "getFuncs(): SELECT failed\n");
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numFuncs = ntups;

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

	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));
1385
		finfo[i].lang = atoi(PQgetvalue(res, i, i_prolang));
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398

		finfo[i].usename = strdup(PQgetvalue(res, i, i_usename));

		parseArgTypes(finfo[i].argtypes, PQgetvalue(res, i, i_proargtypes));

		finfo[i].dumped = 0;
	}

	PQclear(res);
	res = PQexec(g_conn, "end");
	PQclear(res);

	return finfo;
1399 1400 1401 1402 1403

}

/*
 * getTables
1404
 *	  read all the user-defined tables (no indices, no catalogs)
1405 1406
 * in the system catalogs return them in the TableInfo* structure
 *
1407 1408
 * numTables is set to the number of tables read in
 *
1409 1410
 *
 */
1411
TableInfo  *
V
Vadim B. Mikheev 已提交
1412
getTables(int *numTables, FuncInfo *finfo, int numFuncs)
1413
{
B
Bruce Momjian 已提交
1414
	PGresult		*res;
1415 1416
	int			ntups;
	int			i;
B
Bruce Momjian 已提交
1417 1418
	char			query[MAXQUERYLEN];
	TableInfo		*tblinfo;
1419 1420 1421 1422 1423 1424

	int			i_oid;
	int			i_relname;
	int			i_relkind;
	int			i_relacl;
	int			i_usename;
V
Vadim B. Mikheev 已提交
1425 1426
	int			i_relchecks;
	int			i_reltriggers;
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445

	/*
	 * 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*
	 *
	 * we ignore tables that start with xinv
	 */

	res = PQexec(g_conn, "begin");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, "BEGIN command failed\n");
		exit_nicely(g_conn);
	}
	PQclear(res);

	sprintf(query,
1446 1447
			"SELECT pg_class.oid, relname, relkind, relacl, usename, "
			"relchecks, reltriggers "
1448 1449 1450
			"from pg_class, pg_user "
			"where relowner = usesysid and "
			"(relkind = 'r' or relkind = 'S') and relname !~ '^pg_' "
1451
			"order by oid");
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471

	res = PQexec(g_conn, query);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, "getTables(): SELECT failed\n");
		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 已提交
1472 1473
	i_relchecks = PQfnumber(res, "relchecks");
	i_reltriggers = PQfnumber(res, "reltriggers");
1474 1475 1476 1477 1478 1479 1480 1481

	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 已提交
1482 1483
		tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
		tblinfo[i].ntrig = atoi(PQgetvalue(res, i, i_reltriggers));
1484

1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
		/* Exclude inherited CHECKs from CHECK constraints total.
		 * If a constraint matches by name and condition with a constraint
		 * belonging to a parent class, we assume it was inherited.
		 */
		if (tblinfo[i].ncheck > 0)
		{
			PGresult	*res2;
			int			ntups2;

 			if (g_verbose)
				fprintf(stderr, "%s excluding inherited CHECK constraints "
						"for relation: '%s' %s\n",
						g_comment_start,
						tblinfo[i].relname,
						g_comment_end);

			sprintf(query, "SELECT rcname from pg_relcheck, pg_inherits as i "
					"where rcrelid = '%s'::oid "
					" and rcrelid = i.inhrel"
					" 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);
			res2 = PQexec(g_conn, query);
			if (!res2 ||
				PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
				fprintf(stderr, "getTables(): SELECT (for inherited CHECK) failed\n");
				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 已提交
1530 1531 1532
		if (tblinfo[i].ncheck > 0)
		{
			PGresult   *res2;
1533 1534
			int			i_rcname,
						i_rcsrc;
V
Vadim B. Mikheev 已提交
1535 1536
			int			ntups2;
			int			i2;
1537

V
Vadim B. Mikheev 已提交
1538
			if (g_verbose)
1539
				fprintf(stderr, "%s finding CHECK constraints for relation: '%s' %s\n",
V
Vadim B. Mikheev 已提交
1540 1541 1542
						g_comment_start,
						tblinfo[i].relname,
						g_comment_end);
1543

V
Vadim B. Mikheev 已提交
1544
			sprintf(query, "SELECT rcname, rcsrc from pg_relcheck "
1545 1546 1547 1548 1549 1550 1551
					"where rcrelid = '%s'::oid "
					"   and not exists "
					"  (select * from pg_relcheck as c, pg_inherits as i "
					"   where i.inhrel = pg_relcheck.rcrelid "
					"     and c.rcname = pg_relcheck.rcname "
					"     and c.rcsrc = pg_relcheck.rcsrc "
					"     and c.rcrelid = i.inhparent) ",
V
Vadim B. Mikheev 已提交
1552 1553 1554
					tblinfo[i].oid);
			res2 = PQexec(g_conn, query);
			if (!res2 ||
1555
				PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
1556 1557 1558 1559 1560 1561 1562
			{
				fprintf(stderr, "getTables(): SELECT (for CHECK) failed\n");
				exit_nicely(g_conn);
			}
			ntups2 = PQntuples(res2);
			if (ntups2 != tblinfo[i].ncheck)
			{
1563
				fprintf(stderr, "getTables(): relation '%s': %d CHECKs were expected, but got %d\n",
1564
						tblinfo[i].relname, tblinfo[i].ncheck, ntups2);
V
Vadim B. Mikheev 已提交
1565 1566 1567 1568
				exit_nicely(g_conn);
			}
			i_rcname = PQfnumber(res2, "rcname");
			i_rcsrc = PQfnumber(res2, "rcsrc");
1569
			tblinfo[i].check_expr = (char **) malloc(ntups2 * sizeof(char *));
V
Vadim B. Mikheev 已提交
1570 1571
			for (i2 = 0; i2 < ntups2; i2++)
			{
1572 1573 1574
				char	   *name = PQgetvalue(res2, i2, i_rcname);
				char	   *expr = PQgetvalue(res2, i2, i_rcsrc);

1575
				query[0] = '\0';
1576
				if (name[0] != '$')
1577
					sprintf(query, "CONSTRAINT %s ", fmtId(name, force_quotes));
1578
				sprintf(query + strlen(query), "CHECK (%s)", expr);
1579
				tblinfo[i].check_expr[i2] = strdup(query);
V
Vadim B. Mikheev 已提交
1580 1581 1582 1583 1584
			}
			PQclear(res2);
		}
		else
			tblinfo[i].check_expr = NULL;
1585

V
Vadim B. Mikheev 已提交
1586 1587 1588 1589
		/* Get Triggers */
		if (tblinfo[i].ntrig > 0)
		{
			PGresult   *res2;
1590 1591 1592 1593 1594
			int			i_tgname,
						i_tgfoid,
						i_tgtype,
						i_tgnargs,
						i_tgargs;
V
Vadim B. Mikheev 已提交
1595 1596
			int			ntups2;
			int			i2;
1597

V
Vadim B. Mikheev 已提交
1598
			if (g_verbose)
1599
				fprintf(stderr, "%s finding Triggers for relation: '%s' %s\n",
V
Vadim B. Mikheev 已提交
1600 1601 1602
						g_comment_start,
						tblinfo[i].relname,
						g_comment_end);
1603

V
Vadim B. Mikheev 已提交
1604 1605 1606 1607 1608 1609
			sprintf(query, "SELECT tgname, tgfoid, tgtype, tgnargs, tgargs "
					"from pg_trigger "
					"where tgrelid = '%s'::oid ",
					tblinfo[i].oid);
			res2 = PQexec(g_conn, query);
			if (!res2 ||
1610
				PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
1611 1612 1613 1614 1615 1616 1617
			{
				fprintf(stderr, "getTables(): SELECT (for TRIGGER) failed\n");
				exit_nicely(g_conn);
			}
			ntups2 = PQntuples(res2);
			if (ntups2 != tblinfo[i].ntrig)
			{
1618
				fprintf(stderr, "getTables(): relation '%s': %d Triggers were expected, but got %d\n",
1619
						tblinfo[i].relname, tblinfo[i].ntrig, ntups2);
V
Vadim B. Mikheev 已提交
1620 1621 1622 1623 1624 1625 1626
				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");
1627
			tblinfo[i].triggers = (char **) malloc(ntups2 * sizeof(char *));
V
Vadim B. Mikheev 已提交
1628 1629
			for (i2 = 0, query[0] = 0; i2 < ntups2; i2++)
			{
1630 1631 1632 1633 1634 1635 1636 1637
				char	   *tgfunc = PQgetvalue(res2, i2, i_tgfoid);
				int2		tgtype = atoi(PQgetvalue(res2, i2, i_tgtype));
				int			tgnargs = atoi(PQgetvalue(res2, i2, i_tgnargs));
				char	   *tgargs = PQgetvalue(res2, i2, i_tgargs);
				char	   *p;
				char		farg[MAXQUERYLEN];
				int			findx;

V
Vadim B. Mikheev 已提交
1638 1639 1640
				for (findx = 0; findx < numFuncs; findx++)
				{
					if (strcmp(finfo[findx].oid, tgfunc) == 0 &&
1641
						finfo[findx].nargs == 0 &&
V
Vadim B. Mikheev 已提交
1642 1643 1644 1645 1646
						strcmp(finfo[findx].prorettype, "0") == 0)
						break;
				}
				if (findx == numFuncs)
				{
1647
					fprintf(stderr, "getTables(): relation '%s': cannot find function with oid %s for trigger %s\n",
1648
							tblinfo[i].relname, tgfunc, PQgetvalue(res2, i2, i_tgname));
V
Vadim B. Mikheev 已提交
1649 1650 1651
					exit_nicely(g_conn);
				}
				tgfunc = finfo[findx].proname;
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663

#if 0				
				/* XXX - how to emit this DROP TRIGGER? */
				if (drop_schema)
				  {
				    sprintf(query, "DROP TRIGGER %s ON %s;\n",
					    fmtId(PQgetvalue(res2, i2, i_tgname), force_quotes),
					    fmtId(tblinfo[i].relname, force_quotes));
				    fputs(query, fout);
				  }
#endif

1664
				sprintf(query, "CREATE TRIGGER %s ", fmtId(PQgetvalue(res2, i2, i_tgname), force_quotes));
V
Vadim B. Mikheev 已提交
1665 1666 1667
				/* Trigger type */
				findx = 0;
				if (TRIGGER_FOR_BEFORE(tgtype))
1668
					strcat(query, "BEFORE");
V
Vadim B. Mikheev 已提交
1669
				else
1670
					strcat(query, "AFTER");
V
Vadim B. Mikheev 已提交
1671 1672
				if (TRIGGER_FOR_INSERT(tgtype))
				{
1673
					strcat(query, " INSERT");
V
Vadim B. Mikheev 已提交
1674 1675 1676 1677 1678
					findx++;
				}
				if (TRIGGER_FOR_DELETE(tgtype))
				{
					if (findx > 0)
1679
						strcat(query, " OR DELETE");
V
Vadim B. Mikheev 已提交
1680
					else
1681
						strcat(query, " DELETE");
V
Vadim B. Mikheev 已提交
1682 1683 1684
					findx++;
				}
				if (TRIGGER_FOR_UPDATE(tgtype))
1685
				{
V
Vadim B. Mikheev 已提交
1686
					if (findx > 0)
1687
						strcat(query, " OR UPDATE");
V
Vadim B. Mikheev 已提交
1688
					else
1689
						strcat(query, " UPDATE");
1690
				}
1691
				sprintf(query, "%s ON %s FOR EACH ROW EXECUTE PROCEDURE %s (",
1692
						query, fmtId(tblinfo[i].relname, force_quotes), tgfunc);
V
Vadim B. Mikheev 已提交
1693 1694
				for (findx = 0; findx < tgnargs; findx++)
				{
1695 1696 1697 1698
					char	   *s,
							   *d;

					for (p = tgargs;;)
V
Vadim B. Mikheev 已提交
1699
					{
1700
						p = strchr(p, '\\');
V
Vadim B. Mikheev 已提交
1701 1702
						if (p == NULL)
						{
1703
							fprintf(stderr, "getTables(): relation '%s': bad argument string (%s) for trigger '%s'\n",
1704 1705 1706
									tblinfo[i].relname,
									PQgetvalue(res2, i2, i_tgargs),
									PQgetvalue(res2, i2, i_tgname));
V
Vadim B. Mikheev 已提交
1707 1708 1709 1710 1711 1712 1713 1714
							exit_nicely(g_conn);
						}
						p++;
						if (*p == '\\')
						{
							p++;
							continue;
						}
1715
						if (p[0] == '0' && p[1] == '0' && p[2] == '0')
V
Vadim B. Mikheev 已提交
1716 1717 1718
							break;
					}
					p--;
1719
					for (s = tgargs, d = &(farg[0]); s < p;)
V
Vadim B. Mikheev 已提交
1720 1721 1722 1723 1724 1725
					{
						if (*s == '\'')
							*d++ = '\\';
						*d++ = *s++;
					}
					*d = 0;
1726 1727
					sprintf(query, "%s'%s'%s", query, farg,
							(findx < tgnargs - 1) ? ", " : "");
V
Vadim B. Mikheev 已提交
1728 1729
					tgargs = p + 4;
				}
1730 1731
				strcat(query, ");\n");
				tblinfo[i].triggers[i2] = strdup(query);
V
Vadim B. Mikheev 已提交
1732 1733 1734 1735 1736
			}
			PQclear(res2);
		}
		else
			tblinfo[i].triggers = NULL;
1737 1738 1739 1740 1741 1742 1743
	}

	PQclear(res);
	res = PQexec(g_conn, "end");
	PQclear(res);

	return tblinfo;
1744 1745 1746 1747 1748

}

/*
 * getInherits
1749
 *	  read all the inheritance information
1750 1751
 * from the system catalogs return them in the InhInfo* structure
 *
1752 1753
 * numInherits is set to the number of tables read in
 *
1754 1755
 *
 */
1756
InhInfo    *
1757 1758
getInherits(int *numInherits)
{
B
Bruce Momjian 已提交
1759
	PGresult		*res;
1760 1761
	int			ntups;
	int			i;
B
Bruce Momjian 已提交
1762 1763
	char			query[MAXQUERYLEN];
	InhInfo			*inhinfo;
1764

1765 1766
	int			i_inhrel;
	int			i_inhparent;
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806

	/* find all the inheritance information */
	res = PQexec(g_conn, "begin");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, "BEGIN command failed\n");
		exit_nicely(g_conn);
	}
	PQclear(res);

	sprintf(query, "SELECT inhrel, inhparent from pg_inherits");

	res = PQexec(g_conn, query);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, "getInherits(): SELECT failed\n");
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numInherits = ntups;

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

	i_inhrel = PQfnumber(res, "inhrel");
	i_inhparent = PQfnumber(res, "inhparent");

	for (i = 0; i < ntups; i++)
	{
		inhinfo[i].inhrel = strdup(PQgetvalue(res, i, i_inhrel));
		inhinfo[i].inhparent = strdup(PQgetvalue(res, i, i_inhparent));
	}

	PQclear(res);
	res = PQexec(g_conn, "end");
	PQclear(res);
	return inhinfo;
1807 1808 1809 1810
}

/*
 * getTableAttrs -
1811 1812
 *	  for each table in tblinfo, read its attributes types and names
 *
1813
 * this is implemented in a very inefficient way right now, looping
1814
 * through the tblinfo and doing a join per table to find the attrs and their
1815 1816
 * types
 *
1817
 *	modifies tblinfo
1818 1819
 */
void
1820
getTableAttrs(TableInfo *tblinfo, int numTables)
1821
{
1822 1823
	int			i,
				j;
B
Bruce Momjian 已提交
1824
	char			q[MAXQUERYLEN];
1825 1826
	int			i_attname;
	int			i_typname;
1827
	int			i_atttypmod;
1828
	int			i_attnotnull;
V
Vadim B. Mikheev 已提交
1829
	int			i_atthasdef;
B
Bruce Momjian 已提交
1830
	PGresult		*res;
1831
	int			ntups;
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846

	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)
1847
			fprintf(stderr, "%s finding the attrs and types for table: '%s' %s\n",
1848 1849 1850 1851
					g_comment_start,
					tblinfo[i].relname,
					g_comment_end);

1852
		sprintf(q, "SELECT a.attnum, a.attname, t.typname, a.atttypmod, "
V
Vadim B. Mikheev 已提交
1853
				"a.attnotnull, a.atthasdef "
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
				"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);
		res = PQexec(g_conn, q);
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
			fprintf(stderr, "getTableAttrs(): SELECT failed\n");
			exit_nicely(g_conn);
		}

		ntups = PQntuples(res);

		i_attname = PQfnumber(res, "attname");
		i_typname = PQfnumber(res, "typname");
1870
		i_atttypmod = PQfnumber(res, "atttypmod");
1871
		i_attnotnull = PQfnumber(res, "attnotnull");
V
Vadim B. Mikheev 已提交
1872
		i_atthasdef = PQfnumber(res, "atthasdef");
1873 1874 1875 1876

		tblinfo[i].numatts = ntups;
		tblinfo[i].attnames = (char **) malloc(ntups * sizeof(char *));
		tblinfo[i].typnames = (char **) malloc(ntups * sizeof(char *));
1877
		tblinfo[i].atttypmod = (int *) malloc(ntups * sizeof(int));
1878 1879
		tblinfo[i].inhAttrs = (int *) malloc(ntups * sizeof(int));
		tblinfo[i].notnull = (bool *) malloc(ntups * sizeof(bool));
V
Vadim B. Mikheev 已提交
1880
		tblinfo[i].adef_expr = (char **) malloc(ntups * sizeof(char *));
1881 1882 1883 1884 1885 1886
		tblinfo[i].parentRels = NULL;
		tblinfo[i].numParents = 0;
		for (j = 0; j < ntups; j++)
		{
			tblinfo[i].attnames[j] = strdup(PQgetvalue(res, j, i_attname));
			tblinfo[i].typnames[j] = strdup(PQgetvalue(res, j, i_typname));
1887
			tblinfo[i].atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
1888 1889 1890
			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 已提交
1891 1892 1893
			if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
			{
				PGresult   *res2;
1894

V
Vadim B. Mikheev 已提交
1895
				if (g_verbose)
1896
					fprintf(stderr, "%s finding DEFAULT expression for attr: '%s' %s\n",
V
Vadim B. Mikheev 已提交
1897 1898 1899
							g_comment_start,
							tblinfo[i].attnames[j],
							g_comment_end);
1900

V
Vadim B. Mikheev 已提交
1901 1902 1903 1904 1905
				sprintf(q, "SELECT adsrc from pg_attrdef "
						"where adrelid = '%s'::oid and adnum = %d ",
						tblinfo[i].oid, j + 1);
				res2 = PQexec(g_conn, q);
				if (!res2 ||
1906
					PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
1907 1908 1909 1910 1911 1912 1913 1914 1915
				{
					fprintf(stderr, "getTableAttrs(): SELECT (for DEFAULT) failed\n");
					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;
1916 1917 1918
		}
		PQclear(res);
	}
1919 1920 1921 1922 1923
}


/*
 * getIndices
1924
 *	  read all the user-defined indices information
1925 1926
 * from the system catalogs return them in the InhInfo* structure
 *
1927 1928
 * numIndices is set to the number of indices read in
 *
1929 1930
 *
 */
1931
IndInfo    *
1932 1933
getIndices(int *numIndices)
{
1934
	int			i;
B
Bruce Momjian 已提交
1935 1936
	char			query[MAXQUERYLEN];
	PGresult		*res;
1937
	int			ntups;
B
Bruce Momjian 已提交
1938
	IndInfo			*indinfo;
1939 1940 1941 1942 1943 1944 1945 1946

	int			i_indexrelname;
	int			i_indrelname;
	int			i_indamname;
	int			i_indproc;
	int			i_indkey;
	int			i_indclass;
	int			i_indisunique;
1947 1948 1949 1950 1951

	/*
	 * find all the user-defined indices. We do not handle partial
	 * indices.
	 *
1952
	 * skip 'xinx*' - indices on inversion objects
1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971
	 *
	 * this is a 4-way join !!
	 */

	res = PQexec(g_conn, "begin");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, "BEGIN command failed\n");
		exit_nicely(g_conn);
	}
	PQclear(res);

	sprintf(query,
		  "SELECT 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 "
1972
			"and t1.relam = a.oid and i.indexrelid > '%u'::oid "
1973
			"and t2.relname !~ '^pg_' and t1.relkind != 'l'",
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
			g_last_builtin_oid);

	res = PQexec(g_conn, query);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, "getIndices(): SELECT failed\n");
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numIndices = ntups;

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

	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++)
	{
		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));
		parseArgTypes((char **) indinfo[i].indkey,
					  (const char *) PQgetvalue(res, i, i_indkey));
		parseArgTypes((char **) indinfo[i].indclass,
					  (const char *) PQgetvalue(res, i, i_indclass));
		indinfo[i].indisunique = strdup(PQgetvalue(res, i, i_indisunique));
	}
	PQclear(res);
	res = PQexec(g_conn, "end");
	if (res)
		PQclear(res);
	return indinfo;
2015 2016 2017 2018
}

/*
 * dumpTypes
2019
 *	  writes out to fout the queries to recreate all the user-defined types
2020 2021 2022
 *
 */
void
2023 2024
dumpTypes(FILE *fout, FuncInfo *finfo, int numFuncs,
		  TypeInfo *tinfo, int numTypes)
2025
{
2026
	int			i;
B
Bruce Momjian 已提交
2027
	char			q[MAXQUERYLEN];
2028
	int			funcInd;
2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057

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

2058
		becomeUser(fout, tinfo[i].usename);
2059

2060 2061 2062 2063 2064 2065
		if (drop_schema)
		  {
		    sprintf(q, "DROP TYPE %s;\n", fmtId(tinfo[i].typname, force_quotes));
		    fputs(q, fout);
		  }

2066
		sprintf(q,
2067
				"CREATE TYPE %s "
2068 2069
				"( internallength = %s, externallength = %s, input = %s, "
				"output = %s, send = %s, receive = %s, default = '%s'",
2070
				fmtId(tinfo[i].typname, force_quotes),
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080
				tinfo[i].typlen,
				tinfo[i].typprtlen,
				tinfo[i].typinput,
				tinfo[i].typoutput,
				tinfo[i].typsend,
				tinfo[i].typreceive,
				tinfo[i].typdefault);

		if (tinfo[i].isArray)
		{
2081
			char	   *elemType;
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094

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

			sprintf(q, "%s, element = %s, delimiter = '%s'",
					q, elemType, tinfo[i].typdelim);
		}
		if (tinfo[i].passedbyvalue)
			strcat(q, ",passedbyvalue);\n");
		else
			strcat(q, ");\n");

		fputs(q, fout);
	}
2095 2096
}

2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161
/*
 * dumpProcLangs
 *        writes out to fout the queries to recreate user-defined procedural languages
 *
 */
void
dumpProcLangs(FILE *fout, FuncInfo *finfo, int numFuncs,
		  TypeInfo *tinfo, int numTypes)
{
	PGresult		*res;
	char			query[MAXQUERYLEN];
	int			ntups;
	int			i_lanname;
	int			i_lanpltrusted;
	int			i_lanplcallfoid;
	int			i_lancompiler;
	char			*lanname;
	char			*lancompiler;
	char			*lanplcallfoid;
	int			i,
				fidx;

	res = PQexec(g_conn, "begin");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, "BEGIN command failed\n");
		exit_nicely(g_conn);
	}

	sprintf(query, "SELECT * FROM pg_language "
			"WHERE lanispl "
			"ORDER BY oid");
	res = PQexec(g_conn, query);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, "dumpProcLangs(): SELECT failed\n");
		exit_nicely(g_conn);
	}
	ntups = PQntuples(res);

	i_lanname	= PQfnumber(res, "lanname");
	i_lanpltrusted	= PQfnumber(res, "lanpltrusted");
	i_lanplcallfoid	= PQfnumber(res, "lanplcallfoid");
	i_lancompiler	= PQfnumber(res, "lancompiler");

	for (i = 0; i < ntups; i++) {
		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));

2162 2163 2164
		if (drop_schema)
		  fprintf(fout, "DROP PROCEDURAL LANGUAGE '%s';\n", lanname);

2165 2166 2167 2168
		fprintf(fout, "CREATE %sPROCEDURAL LANGUAGE '%s' "
			"HANDLER %s LANCOMPILER '%s';\n",
			(PQgetvalue(res, i, i_lanpltrusted)[0] == 't') ? "TRUSTED " : "",
			lanname,
2169
			fmtId(finfo[fidx].proname, force_quotes),
2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181
			lancompiler);

		free(lanname);
		free(lancompiler);
	}

	PQclear(res);

	res = PQexec(g_conn, "end");
	PQclear(res);
}

2182 2183
/*
 * dumpFuncs
2184
 *	  writes out to fout the queries to recreate all the user-defined functions
2185 2186 2187
 *
 */
void
2188 2189
dumpFuncs(FILE *fout, FuncInfo *finfo, int numFuncs,
		  TypeInfo *tinfo, int numTypes)
2190
{
2191
	int			i;
2192 2193 2194

	for (i = 0; i < numFuncs; i++)
		dumpOneFunc(fout, finfo, i, tinfo, numTypes);
2195 2196 2197 2198
}

/*
 * dumpOneFunc:
2199 2200
 *	  dump out only one function,  the index of which is given in the third
 *	argument
2201 2202 2203
 *
 */

2204
static void
2205 2206
dumpOneFunc(FILE *fout, FuncInfo *finfo, int i,
			TypeInfo *tinfo, int numTypes)
2207
{
2208
	char		q[MAXQUERYLEN];
B
Bruce Momjian 已提交
2209
	int		j;
2210 2211
	char		*func_def;
	char		func_lang[NAMEDATALEN + 1];
2212 2213 2214 2215 2216 2217

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

2218
	becomeUser(fout, finfo[i].usename);
2219

2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
	if (finfo[i].lang == INTERNALlanguageId)
	{
		func_def = finfo[i].prosrc;
		strcpy(func_lang, "INTERNAL");
	}
	else if (finfo[i].lang == ClanguageId)
	{
		func_def = finfo[i].probin;
		strcpy(func_lang, "C");
	}
	else if (finfo[i].lang == SQLlanguageId)
	{
		func_def = finfo[i].prosrc;
		strcpy(func_lang, "SQL");
	}
	else
	{
		PGresult	*res;
		int		nlangs;
		int		i_lanname;
		char		query[256];

		res = PQexec(g_conn, "begin");
		if (!res ||
			PQresultStatus(res) != PGRES_COMMAND_OK)
		{
			fprintf(stderr, "dumpOneFunc(): BEGIN command failed\n");
			exit_nicely(g_conn);
		}
		PQclear(res);

		sprintf(query, "SELECT lanname FROM pg_language "
2252
				"WHERE oid = %u",
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279
				finfo[i].lang);
		res = PQexec(g_conn, query);
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
			fprintf(stderr, "dumpOneFunc(): SELECT for procedural language failed\n");
			exit_nicely(g_conn);
		}
		nlangs = PQntuples(res);

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

		i_lanname = PQfnumber(res, "lanname");

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

		PQclear(res);

		res = PQexec(g_conn, "end");
		PQclear(res);
	}

2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
	if (drop_schema)
	  {
	    sprintf(q, "DROP FUNCTION %s (", fmtId(finfo[i].proname, force_quotes));
	    for (j = 0; j < finfo[i].nargs; j++)
	      {
		char	   *typname;
		
		typname = findTypeByOid(tinfo, numTypes, finfo[i].argtypes[j]);
		sprintf(q, "%s%s%s",
			q,
			(j > 0) ? "," : "",
			fmtId(typname, false));
	      }
	    sprintf (q, "%s);\n", q);
	    fputs(q, fout);
	  }

2297
	sprintf(q, "CREATE FUNCTION %s (", fmtId(finfo[i].proname, force_quotes));
2298 2299
	for (j = 0; j < finfo[i].nargs; j++)
	{
2300
		char	   *typname;
2301 2302

		typname = findTypeByOid(tinfo, numTypes, finfo[i].argtypes[j]);
2303
		sprintf(q, "%s%s%s",
2304 2305
				q,
				(j > 0) ? "," : "",
2306
				fmtId(typname, false));
2307 2308 2309 2310
	}
	sprintf(q, "%s ) RETURNS %s%s AS '%s' LANGUAGE '%s';\n",
			q,
			(finfo[i].retset) ? " SETOF " : "",
2311
			fmtId(findTypeByOid(tinfo, numTypes, finfo[i].prorettype), false),
2312
			func_def, func_lang);
2313 2314

	fputs(q, fout);
2315 2316 2317 2318 2319

}

/*
 * dumpOprs
2320
 *	  writes out to fout the queries to recreate all the user-defined operators
2321 2322
 *
 */
2323
void
2324 2325
dumpOprs(FILE *fout, OprInfo *oprinfo, int numOperators,
		 TypeInfo *tinfo, int numTypes)
2326
{
B
Bruce Momjian 已提交
2327
	int		i;
2328 2329 2330 2331 2332
	char		q[MAXQUERYLEN];
	char		leftarg[MAXQUERYLEN];
	char		rightarg[MAXQUERYLEN];
	char		commutator[MAXQUERYLEN];
	char		negator[MAXQUERYLEN];
B
Bruce Momjian 已提交
2333
	char		restrictor[MAXQUERYLEN];
2334
	char		join[MAXQUERYLEN];
2335 2336
	char		sort1[MAXQUERYLEN];
	char		sort2[MAXQUERYLEN];
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361

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

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

		leftarg[0] = '\0';
		rightarg[0] = '\0';

		/*
		 * 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)
		{
2362
			sprintf(leftarg, ",\n\tLEFTARG = %s ",
2363
			  fmtId(findTypeByOid(tinfo, numTypes, oprinfo[i].oprleft), false));
2364 2365 2366 2367
		}
		if (strcmp(oprinfo[i].oprkind, "l") == 0 ||
			strcmp(oprinfo[i].oprkind, "b") == 0)
		{
2368
			sprintf(rightarg, ",\n\tRIGHTARG = %s ",
2369
			 fmtId(findTypeByOid(tinfo, numTypes, oprinfo[i].oprright), false));
2370 2371 2372 2373
		}
		if (strcmp(oprinfo[i].oprcom, "0") == 0)
			commutator[0] = '\0';
		else
2374
			sprintf(commutator, ",\n\tCOMMUTATOR = %s ",
2375 2376 2377 2378 2379
				 findOprByOid(oprinfo, numOperators, oprinfo[i].oprcom));

		if (strcmp(oprinfo[i].oprnegate, "0") == 0)
			negator[0] = '\0';
		else
2380
			sprintf(negator, ",\n\tNEGATOR = %s ",
2381 2382 2383
			  findOprByOid(oprinfo, numOperators, oprinfo[i].oprnegate));

		if (strcmp(oprinfo[i].oprrest, "-") == 0)
B
Bruce Momjian 已提交
2384
			restrictor[0] = '\0';
2385
		else
2386
			sprintf(restrictor, ",\n\tRESTRICT = %s ", oprinfo[i].oprrest);
2387 2388 2389 2390

		if (strcmp(oprinfo[i].oprjoin, "-") == 0)
			join[0] = '\0';
		else
2391
			sprintf(join, ",\n\tJOIN = %s ", oprinfo[i].oprjoin);
2392 2393

		if (strcmp(oprinfo[i].oprlsortop, "0") == 0)
2394
			sort1[0] = '\0';
2395
		else
2396 2397 2398 2399 2400 2401 2402 2403
			sprintf(sort1, ",\n\tSORT1 = %s ",
				findOprByOid(oprinfo, numOperators, oprinfo[i].oprlsortop));

		if (strcmp(oprinfo[i].oprrsortop, "0") == 0)
			sort2[0] = '\0';
		else
			sprintf(sort2, ",\n\tSORT2 = %s ",
				findOprByOid(oprinfo, numOperators, oprinfo[i].oprrsortop));
2404

2405
		becomeUser(fout, oprinfo[i].usename);
2406

2407 2408 2409 2410 2411 2412 2413 2414
		if (drop_schema)
		  {
		    sprintf(q, "DROP OPERATOR %s (%s, %s);\n", oprinfo[i].oprname, 
			    fmtId(findTypeByOid(tinfo, numTypes, oprinfo[i].oprleft), false),
			    fmtId(findTypeByOid(tinfo, numTypes, oprinfo[i].oprright), false));
		    fputs(q, fout);
		  }

2415 2416
		sprintf(q,
				"CREATE OPERATOR %s "
2417
				"(PROCEDURE = %s %s%s%s%s%s%s%s%s%s);\n",
2418 2419 2420 2421 2422 2423
				oprinfo[i].oprname,
				oprinfo[i].oprcode,
				leftarg,
				rightarg,
				commutator,
				negator,
B
Bruce Momjian 已提交
2424
				restrictor,
2425
				(strcmp(oprinfo[i].oprcanhash, "t") == 0) ? ",\n\tHASHES" : "",
2426
				join,
2427 2428
				sort1,
				sort2);
2429 2430 2431

		fputs(q, fout);
	}
2432 2433 2434 2435
}

/*
 * dumpAggs
2436
 *	  writes out to fout the queries to create all the user-defined aggregates
2437 2438 2439
 *
 */
void
2440 2441
dumpAggs(FILE *fout, AggInfo *agginfo, int numAggs,
		 TypeInfo *tinfo, int numTypes)
2442
{
B
Bruce Momjian 已提交
2443
	int		i;
2444 2445 2446
	char		q[MAXQUERYLEN];
	char		sfunc1[MAXQUERYLEN];
	char		sfunc2[MAXQUERYLEN];
V
Vadim B. Mikheev 已提交
2447
	char		basetype[MAXQUERYLEN];
2448 2449
	char		finalfunc[MAXQUERYLEN];
	char		comma1[2],
B
Bruce Momjian 已提交
2450
			comma2[2];
2451 2452 2453 2454 2455 2456

	for (i = 0; i < numAggs; i++)
	{
		/* skip all the builtin oids */
		if (atoi(agginfo[i].oid) < g_last_builtin_oid)
			continue;
2457

V
Vadim B. Mikheev 已提交
2458 2459
		sprintf(basetype,
				"BASETYPE = %s, ",
2460
		  fmtId(findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype), false));
2461 2462 2463 2464 2465 2466

		if (strcmp(agginfo[i].aggtransfn1, "-") == 0)
			sfunc1[0] = '\0';
		else
		{
			sprintf(sfunc1,
V
Vadim B. Mikheev 已提交
2467
					"SFUNC1 = %s, STYPE1 = %s",
2468
					agginfo[i].aggtransfn1,
2469
					fmtId(findTypeByOid(tinfo, numTypes, agginfo[i].aggtranstype1), false));
2470
			if (agginfo[i].agginitval1)
V
Vadim B. Mikheev 已提交
2471
				sprintf(sfunc1, "%s, INITCOND1 = '%s'",
2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482
						sfunc1, agginfo[i].agginitval1);

		}

		if (strcmp(agginfo[i].aggtransfn2, "-") == 0)
			sfunc2[0] = '\0';
		else
		{
			sprintf(sfunc2,
					"SFUNC2 = %s, STYPE2 = %s",
					agginfo[i].aggtransfn2,
2483
					fmtId(findTypeByOid(tinfo, numTypes, agginfo[i].aggtranstype2), false));
2484
			if (agginfo[i].agginitval2)
V
Vadim B. Mikheev 已提交
2485
				sprintf(sfunc2, "%s, INITCOND2 = '%s'",
2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508
						sfunc2, agginfo[i].agginitval2);
		}

		if (strcmp(agginfo[i].aggfinalfn, "-") == 0)
			finalfunc[0] = '\0';
		else
			sprintf(finalfunc, "FINALFUNC = %s", agginfo[i].aggfinalfn);
		if (sfunc1[0] != '\0' && sfunc2[0] != '\0')
		{
			comma1[0] = ',';
			comma1[1] = '\0';
		}
		else
			comma1[0] = '\0';

		if (finalfunc[0] != '\0' && (sfunc1[0] != '\0' || sfunc2[0] != '\0'))
		{
			comma2[0] = ',';
			comma2[1] = '\0';
		}
		else
			comma2[0] = '\0';

2509
		becomeUser(fout, agginfo[i].usename);
2510

2511 2512 2513 2514 2515 2516 2517
		if (drop_schema)
		  {
		    sprintf(q, "DROP AGGREGATE %s %s;\n", agginfo[i].aggname,
			    fmtId(findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype), false));
		    fputs(q, fout);
		  }

V
Vadim B. Mikheev 已提交
2518
		sprintf(q, "CREATE AGGREGATE %s ( %s %s%s %s%s %s );\n",
2519
				agginfo[i].aggname,
V
Vadim B. Mikheev 已提交
2520
				basetype,
2521 2522 2523 2524 2525 2526 2527 2528
				sfunc1,
				comma1,
				sfunc2,
				comma2,
				finalfunc);

		fputs(q, fout);
	}
2529 2530
}

2531 2532 2533 2534 2535
/*
 * These are some support functions to fix the acl problem of pg_dump
 *
 * Matthew C. Aycock 12/02/97
 */
2536 2537 2538

/* Append a keyword to a keyword list, inserting comma if needed.
 * Caller must make aclbuf big enough for all possible keywords.
2539
 */
2540 2541
static void
AddAcl (char *aclbuf, const char *keyword)
2542
{
2543 2544 2545
	if (*aclbuf)
		strcat(aclbuf, ",");
	strcat(aclbuf, keyword);
2546
}
2547

2548
/*
2549
 * This will take a string of 'arwR' and return a malloced,
2550 2551
 * comma delimited string of SELECT,INSERT,UPDATE,DELETE,RULE
 */
V
Vadim B. Mikheev 已提交
2552
static char *
2553
GetPrivileges(const char *s)
2554
{
2555
	char		aclbuf[100];
2556

2557
	aclbuf[0] = '\0';
2558

B
Bruce Momjian 已提交
2559
	if (strchr(s, 'a'))
2560
		AddAcl(aclbuf, "INSERT");
2561

B
Bruce Momjian 已提交
2562
	if (strchr(s, 'w'))
2563
		AddAcl(aclbuf, "UPDATE,DELETE");
B
Bruce Momjian 已提交
2564 2565

	if (strchr(s, 'r'))
2566
		AddAcl(aclbuf, "SELECT");
2567

2568
	if (strchr(s, 'R'))
2569
		AddAcl(aclbuf, "RULE");
2570

2571 2572 2573
	/* Special-case when they're all there */
	if (strcmp(aclbuf, "INSERT,UPDATE,DELETE,SELECT,RULE") == 0)
		return strdup("ALL");
2574

2575
	return strdup(aclbuf);
2576
}
2577

B
Bruce Momjian 已提交
2578 2579
/*
 * dumpACL:
2580 2581
 *	  Write out grant/revoke information
 *	  Called for sequences and tables
B
Bruce Momjian 已提交
2582 2583
 */

2584
static void
B
Bruce Momjian 已提交
2585 2586
dumpACL(FILE *fout, TableInfo tbinfo)
{
2587 2588
	const char *acls = tbinfo.relacl;
	char	   *aclbuf,
B
Bruce Momjian 已提交
2589 2590 2591
		   *tok,
		   *eqpos,
		   *priv;
2592 2593 2594 2595 2596 2597 2598 2599 2600

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

	/* Revoke Default permissions for PUBLIC.
	 * Is this actually necessary, or is it just a waste of time?
	 */
	fprintf(fout,
			"REVOKE ALL on %s from PUBLIC;\n",
2601
			fmtId(tbinfo.relname, force_quotes));
2602 2603 2604

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

2606 2607
	/* Scan comma-separated ACL items */
	for (tok = strtok(aclbuf, ","); tok != NULL; tok = strtok(NULL, ","))
2608
	{
2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619
		/* Token may start with '{' and/or '"'.  Actually only the start of
		 * the string should have '{', but we don't verify that.
		 */
		if (*tok == '{')
			tok++;
		if (*tok == '"')
			tok++;

		/* User name is string up to = in tok */
		eqpos = strchr(tok, '=');
		if (! eqpos)
B
Bruce Momjian 已提交
2620
		{
2621
			fprintf(stderr, "Could not parse ACL list for '%s'...Exiting!\n",
B
Bruce Momjian 已提交
2622 2623 2624 2625
					tbinfo.relname);
			exit_nicely(g_conn);
		}

2626 2627 2628
		/* Parse the privileges (right-hand side).  Skip if there are none. */
		priv = GetPrivileges(eqpos + 1);
		if (*priv)
2629
		{
2630 2631
			fprintf(fout,
					"GRANT %s on %s to ",
2632
					priv, fmtId(tbinfo.relname, force_quotes));
2633 2634 2635 2636 2637 2638
			/* Note: fmtId() can only be called once per printf, so don't
			 * try to merge printing of username into the above printf.
			 */
			if (eqpos == tok)
			{
				/* Empty left-hand side means "PUBLIC" */
2639
				fprintf(fout, "PUBLIC;\n");
2640
			}
2641
			else
2642 2643
			{
				*eqpos = '\0';	/* it's ok to clobber aclbuf */
2644
				fprintf(fout, "%s;\n", fmtId(tok, force_quotes));
2645
			}
2646
		}
2647
		free(priv);
B
Bruce Momjian 已提交
2648
	}
2649 2650

	free(aclbuf);
B
Bruce Momjian 已提交
2651 2652
}

2653

2654 2655
/*
 * dumpTables:
2656
 *	  write out to fout all the user-define tables
2657
 */
2658

2659
void
2660 2661 2662
dumpTables(FILE *fout, TableInfo *tblinfo, int numTables,
		   InhInfo *inhinfo, int numInherits,
		   TypeInfo *tinfo, int numTypes, const char *tablename,
2663
		   const bool acls)
2664
{
2665 2666
	int			i,
				j,
B
Bruce Momjian 已提交
2667
				k;
B
Bruce Momjian 已提交
2668 2669 2670 2671
	char			q[MAXQUERYLEN];
	char			*serialSeq = NULL;		/* implicit sequence name created by SERIAL datatype */
	const char		*serialSeqSuffix = "_id_seq";	/* suffix for implicit SERIAL sequences */
	char			**parentRels;			/* list of names of parent relations */
2672
	int			numParents;
B
Bruce Momjian 已提交
2673
	int			actual_atts;			/* number of attrs in this CREATE statment */
2674 2675 2676 2677
	int32			tmp_typmod;
	int			precision;
	int			scale;

2678

V
Vadim B. Mikheev 已提交
2679
	/* First - dump SEQUENCEs */
B
Bruce Momjian 已提交
2680 2681 2682 2683 2684 2685
	if (tablename)
	  {
	    serialSeq = malloc (strlen (tablename) + strlen (serialSeqSuffix) + 1);
	    strcpy (serialSeq, tablename);
	    strcat (serialSeq, serialSeqSuffix);
	  }
V
Vadim B. Mikheev 已提交
2686 2687 2688 2689
	for (i = 0; i < numTables; i++)
	{
		if (!(tblinfo[i].sequence))
			continue;
B
Bruce Momjian 已提交
2690 2691
		if (!tablename || (!strcmp(tblinfo[i].relname, tablename))
		    || (serialSeq && !strcmp(tblinfo[i].relname,serialSeq)))
V
Vadim B. Mikheev 已提交
2692
		{
2693
			becomeUser(fout, tblinfo[i].usename);
V
Vadim B. Mikheev 已提交
2694
			dumpSequence(fout, tblinfo[i]);
B
Bruce Momjian 已提交
2695 2696
			if (acls)
				dumpACL(fout, tblinfo[i]);
V
Vadim B. Mikheev 已提交
2697 2698
		}
	}
B
Bruce Momjian 已提交
2699 2700
	if (tablename)
	  free (serialSeq);
2701

2702 2703
	for (i = 0; i < numTables; i++)
	{
2704
		if (tblinfo[i].sequence)/* already dumped */
V
Vadim B. Mikheev 已提交
2705
			continue;
2706 2707 2708 2709

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

2710 2711
			/* Skip VIEW relations */
			/*
2712
			if (isViewRule(tblinfo[i].relname))
2713 2714
				continue;
			*/
2715

2716 2717
			parentRels = tblinfo[i].parentRels;
			numParents = tblinfo[i].numParents;
2718

2719
			becomeUser(fout, tblinfo[i].usename);
2720

2721 2722 2723 2724 2725 2726
			if (drop_schema)
			  {
			    sprintf(q, "DROP TABLE %s;\n", fmtId(tblinfo[i].relname, force_quotes));
			    fputs(q, fout);
			  }

2727
			sprintf(q, "CREATE TABLE %s (\n\t", fmtId(tblinfo[i].relname, force_quotes));
2728 2729 2730 2731
			actual_atts = 0;
			for (j = 0; j < tblinfo[i].numatts; j++)
			{
				if (tblinfo[i].inhAttrs[j] == 0)
B
Hi all  
Bruce Momjian 已提交
2732
				{
2733 2734 2735
					if (actual_atts > 0)
						strcat(q, ",\n\t");
					sprintf(q + strlen(q), "%s ",
2736
							fmtId(tblinfo[i].attnames[j], force_quotes));
2737 2738 2739

					/* Show lengths on bpchar and varchar */
					if (!strcmp(tblinfo[i].typnames[j], "bpchar"))
2740
					{
2741 2742 2743 2744 2745
						int len = (tblinfo[i].atttypmod[j] - VARHDRSZ);
						sprintf(q + strlen(q), "character");
						if (len > 1)
							sprintf(q + strlen(q), "(%d)",
									tblinfo[i].atttypmod[j] - VARHDRSZ);
2746
					}
2747 2748
					else if (!strcmp(tblinfo[i].typnames[j], "varchar"))
					{
2749
						sprintf(q + strlen(q), "character varying");
2750 2751 2752 2753
						if (tblinfo[i].atttypmod[j] != -1)
						{
							sprintf(q + strlen(q), "(%d)",
									tblinfo[i].atttypmod[j] - VARHDRSZ);
2754
						}
2755
					}
2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767
					else if (!strcmp(tblinfo[i].typnames[j], "numeric"))
					{
						sprintf(q + strlen(q), "numeric");
						if (tblinfo[i].atttypmod[j] != -1)
						{
							tmp_typmod = tblinfo[i].atttypmod[j] - VARHDRSZ;
							precision = (tmp_typmod >> 16) & 0xffff;
							scale     = tmp_typmod & 0xffff;
							sprintf(q + strlen(q), "(%d,%d)",
										precision, scale);
						}
					}
2768 2769 2770 2771 2772 2773 2774 2775 2776
					/* char is an internal single-byte data type;
					 * Let's make sure we force it through with quotes.
					 * - thomas 1998-12-13
					 */
					else if (!strcmp(tblinfo[i].typnames[j], "char"))
					{
						sprintf(q + strlen(q), "%s",
								fmtId(tblinfo[i].typnames[j], true));
					}
2777 2778
					else
					{
2779
						sprintf(q + strlen(q), "%s",
2780
								fmtId(tblinfo[i].typnames[j], false));
2781 2782
					}
					if (tblinfo[i].adef_expr[j] != NULL)
2783 2784
						sprintf(q + strlen(q), " DEFAULT %s",
								tblinfo[i].adef_expr[j]);
2785
					if (tblinfo[i].notnull[j])
2786 2787
						strcat(q, " NOT NULL");
					actual_atts++;
2788
				}
2789
			}
B
Hi all  
Bruce Momjian 已提交
2790

2791 2792 2793
			/* put the CONSTRAINTS inside the table def */
			for (k = 0; k < tblinfo[i].ncheck; k++)
			{
2794 2795 2796
				if (actual_atts + k > 0)
					strcat(q, ",\n\t");
				sprintf(q + strlen(q), "%s",
2797 2798
						tblinfo[i].check_expr[k]);
			}
2799

2800 2801 2802 2803
			strcat(q, ")");

			if (numParents > 0)
			{
2804
				strcat(q, "\ninherits (");
2805
				for (k = 0; k < numParents; k++)
B
Hi all  
Bruce Momjian 已提交
2806
				{
2807
					sprintf(q + strlen(q), "%s%s",
2808
							(k > 0) ? ", " : "",
2809
							fmtId(parentRels[k], force_quotes));
B
Hi all  
Bruce Momjian 已提交
2810
				}
2811 2812
				strcat(q, ")");
			}
B
Hi all  
Bruce Momjian 已提交
2813

2814
			strcat(q, ";\n");
B
Bruce Momjian 已提交
2815
			fputs(q, fout);
2816
			if (acls)
B
Bruce Momjian 已提交
2817
				dumpACL(fout, tblinfo[i]);
2818

2819 2820
		}
	}
2821 2822 2823 2824
}

/*
 * dumpIndices:
2825
 *	  write out to fout all the user-define indices
2826
 */
2827
void
2828 2829
dumpIndices(FILE *fout, IndInfo *indinfo, int numIndices,
			TableInfo *tblinfo, int numTables, const char *tablename)
2830
{
2831 2832 2833
	int			i,
				k;
	int			tableInd;
B
Bruce Momjian 已提交
2834 2835 2836 2837
	char			attlist[1000];
	char			*classname[INDEX_MAX_KEYS];
	char			*funcname;		/* the name of the function to comput the
							 * index key from */
2838 2839 2840
	int			indkey,
				indclass;
	int			nclass;
2841

B
Bruce Momjian 已提交
2842
	char			q[MAXQUERYLEN],
2843 2844
				id1[MAXQUERYLEN],
				id2[MAXQUERYLEN];
2845
	PGresult   *res;
2846 2847 2848 2849

	for (i = 0; i < numIndices; i++)
	{
		tableInd = findTableByName(tblinfo, numTables,
2850 2851 2852 2853 2854 2855 2856
								   indinfo[i].indrelname);
		if (tableInd < 0)
		{
			fprintf(stderr, "failed sanity check, table %s was not found\n",
					indinfo[i].indrelname);
			exit(2);
		}
2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914

		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*
			 */
			sprintf(q,
					"SELECT proname from pg_proc "
					"where pg_proc.oid = '%s'::oid",
					indinfo[i].indproc);
			res = PQexec(g_conn, q);
			if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
			{
				fprintf(stderr, "dumpIndices(): SELECT (funcname) failed\n");
				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;
			sprintf(q,
					"SELECT opcname from pg_opclass "
					"where pg_opclass.oid = '%u'::oid",
					indclass);
			res = PQexec(g_conn, q);
			if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
			{
				fprintf(stderr, "dumpIndices(): SELECT (classname) failed\n");
				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 */
		for (k = 0, attlist[0] = 0; k < INDEX_MAX_KEYS; k++)
		{
2915
			char	   *attname;
2916 2917

			indkey = atoi(indinfo[i].indkey[k]);
B
Bruce Momjian 已提交
2918
			if (indkey == InvalidAttrNumber)
2919 2920 2921 2922 2923 2924 2925
				break;
			indkey--;
			if (indkey == ObjectIdAttributeNumber - 1)
				attname = "oid";
			else
				attname = tblinfo[tableInd].attnames[indkey];
			if (funcname)
2926
				sprintf(attlist + strlen(attlist), "%s%s",
2927
						(k == 0) ? "" : ", ", fmtId(attname, force_quotes));
2928 2929 2930 2931 2932
			else
			{
				if (k >= nclass)
				{
					fprintf(stderr, "dumpIndices(): OpClass not found for "
2933
							"attribute '%s' of index '%s'\n",
2934 2935 2936
							attname, indinfo[i].indexrelname);
					exit_nicely(g_conn);
				}
2937 2938
				strcpy(id1, fmtId(attname, force_quotes));
				strcpy(id2, fmtId(classname[k], force_quotes));
2939
				sprintf(attlist + strlen(attlist), "%s%s %s",
2940
						(k == 0) ? "" : ", ", id1, id2);
2941 2942 2943 2944 2945 2946
				free(classname[k]);
			}
		}

		if (!tablename || (!strcmp(indinfo[i].indrelname, tablename)))
		{
2947 2948 2949 2950 2951
			/* 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.
			 */
			becomeUser(fout, tblinfo[tableInd].usename);
2952

2953 2954
			strcpy(id1, fmtId(indinfo[i].indexrelname, force_quotes));
			strcpy(id2, fmtId(indinfo[i].indrelname, force_quotes));
2955 2956 2957 2958 2959 2960 2961

			if (drop_schema)
			  {
			    sprintf(q, "DROP INDEX %s;\n", id1);
			    fputs(q, fout);
			  }

2962
			fprintf(fout, "CREATE %s INDEX %s on %s using %s (",
2963
			  (strcmp(indinfo[i].indisunique, "t") == 0) ? "UNIQUE" : "",
2964 2965
					id1,
					id2,
2966 2967 2968
					indinfo[i].indamname);
			if (funcname)
			{
2969
				/* need 2 printf's here cuz fmtId has static return area */
2970 2971
				fprintf(fout, " %s", fmtId(funcname, false));
				fprintf(fout, " (%s) %s );\n", attlist, fmtId(classname[0], force_quotes));
2972 2973 2974 2975
				free(funcname);
				free(classname[0]);
			}
			else
2976
				fprintf(fout, " %s );\n", attlist);
2977 2978
		}
	}
2979 2980

}
2981

2982
/*
2983
 * dumpTuples 
2984 2985 2986 2987 2988
 *	  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
2989
 *	  in PostgreSQL.
2990 2991 2992 2993
 *
 * the attrmap passed in tells how to map the attributes copied in to the
 * attributes copied out
 */
2994
#ifdef NOT_USED
2995
void
2996
dumpTuples(PGresult *res, FILE *fout, int *attrmap)
2997
{
2998 2999 3000 3001
	int			j,
				k;
	int			m,
				n;
B
Bruce Momjian 已提交
3002
	char			**outVals = NULL; /* values to copy out */
3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021

	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++)
			{
3022
				char	   *pval = outVals[k];
3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042

				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);
	}
3043
}
3044

3045
#endif
3046

3047 3048 3049 3050
/*
 * setMaxOid -
 * find the maximum oid and generate a COPY statement to set it
*/
3051

3052
static void
3053
setMaxOid(FILE *fout)
3054
{
B
Bruce Momjian 已提交
3055
	PGresult		*res;
3056
	Oid			max_oid;
3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088

	res = PQexec(g_conn, "CREATE TABLE pgdump_oid (dummy int4)");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, "Can not create pgdump_oid table\n");
		exit_nicely(g_conn);
	}
	PQclear(res);
	res = PQexec(g_conn, "INSERT INTO pgdump_oid VALUES (0)");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, "Can not insert into pgdump_oid table\n");
		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)
	{
		fprintf(stderr, "Can not drop pgdump_oid table\n");
		exit_nicely(g_conn);
	}
	PQclear(res);
	if (g_verbose)
3089
		fprintf(stderr, "%s maximum system oid is %u %s\n",
3090 3091 3092 3093 3094 3095 3096
				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");
}
3097 3098 3099

/*
 * findLastBuiltInOid -
3100
 * find the last built in oid
3101
 * we do this by looking up the oid of 'template1' in pg_database,
3102
 * this is probably not foolproof but comes close
3103 3104
*/

3105
static int
3106
findLastBuiltinOid(void)
3107
{
B
Bruce Momjian 已提交
3108
	PGresult		*res;
3109 3110
	int			ntups;
	int			last_oid;
3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129

	res = PQexec(g_conn,
			  "SELECT oid from pg_database where datname = 'template1'");
	if (res == NULL ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, "pg_dump error in finding the template1 database\n");
		exit_nicely(g_conn);
	}
	ntups = PQntuples(res);
	if (ntups != 1)
	{
		fprintf(stderr, "pg_dump: couldn't find the template1 database.  "
				"You are really hosed.\nGiving up.\n");
		exit_nicely(g_conn);
	}
	last_oid = atoi(PQgetvalue(res, 0, PQfnumber(res, "oid")));
	PQclear(res);
	return last_oid;
3130 3131 3132 3133 3134
}


/*
 * checkForQuote:
3135
 *	  checks a string for quote characters and quotes them
3136
 */
3137
static char *
3138
checkForQuote(const char *s)
3139
{
B
Bruce Momjian 已提交
3140
	char		*r;
3141
	char		c;
B
Bruce Momjian 已提交
3142
	char		*result;
3143

3144
	int			j = 0;
3145

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

3148 3149
	while ((c = *s) != '\0')
	{
3150

3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161
		if (c == '\'')
		{
			r[j++] = '\'';		/* quote the single quotes */
		}
		r[j++] = c;
		s++;
	}
	r[j] = '\0';

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

3163
	return result;
3164 3165

}
3166 3167


3168
static void
3169
dumpSequence(FILE *fout, TableInfo tbinfo)
3170
{
B
Bruce Momjian 已提交
3171 3172
	PGresult		*res;
	int4			last,
3173 3174 3175 3176
				incby,
				maxv,
				minv,
				cache;
B
Bruce Momjian 已提交
3177
	char			cycled,
3178
				called,
B
Bruce Momjian 已提交
3179 3180
				*t;
	char			query[MAXQUERYLEN];
3181 3182 3183

	sprintf(query,
			"SELECT sequence_name, last_value, increment_by, max_value, "
3184
			"min_value, cache_value, is_cycled, is_called from %s",
3185
			fmtId(tbinfo.relname, force_quotes));
3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221

	res = PQexec(g_conn, query);
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, "dumpSequence(%s): SELECT failed\n", tbinfo.relname);
		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);

3222 3223 3224 3225 3226 3227
	if (drop_schema)
	  {
	    sprintf(query, "DROP SEQUENCE %s;\n", fmtId(tbinfo.relname, force_quotes));
	    fputs(query, fout);
	  }

3228
	sprintf(query,
3229
			"CREATE SEQUENCE %s start %d increment %d maxvalue %d "
3230
			"minvalue %d  cache %d %s;\n",
3231
			fmtId(tbinfo.relname, force_quotes), last, incby, maxv, minv, cache,
3232 3233 3234 3235 3236 3237 3238 3239 3240
			(cycled == 't') ? "cycle" : "");

	fputs(query, fout);

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

	sprintf(query, "SELECT nextval ('%s');\n", tbinfo.relname);
	fputs(query, fout);
3241 3242

}
V
Vadim B. Mikheev 已提交
3243 3244


3245 3246 3247
static void
dumpTriggers(FILE *fout, const char *tablename,
			 TableInfo *tblinfo, int numTables)
V
Vadim B. Mikheev 已提交
3248
{
3249 3250 3251
	int			i,
				j;

V
Vadim B. Mikheev 已提交
3252 3253 3254
	if (g_verbose)
		fprintf(stderr, "%s dumping out triggers %s\n",
				g_comment_start, g_comment_end);
3255

V
Vadim B. Mikheev 已提交
3256 3257 3258 3259 3260 3261
	for (i = 0; i < numTables; i++)
	{
		if (tablename && strcmp(tblinfo[i].relname, tablename))
			continue;
		for (j = 0; j < tblinfo[i].ntrig; j++)
		{
3262
			becomeUser(fout, tblinfo[i].usename);
V
Vadim B. Mikheev 已提交
3263 3264 3265 3266
			fputs(tblinfo[i].triggers[j], fout);
		}
	}
}
3267 3268


3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337
static void
dumpRules(FILE *fout, const char *tablename,
			TableInfo *tblinfo, int numTables)
{
	PGresult   	*res;
	int		nrules;
	int		i,
			t;
	char		query[MAXQUERYLEN];

	int		i_definition;

	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;
		res = PQexec(g_conn, "begin");
		if (!res ||
			PQresultStatus(res) != PGRES_COMMAND_OK)
		{
			fprintf(stderr, "BEGIN command failed\n");
			exit_nicely(g_conn);
		}
		PQclear(res);

		/*
		 * Get all rules defined for this table
		 */
		sprintf(query, "SELECT pg_get_ruledef(pg_rewrite.rulename) "
				"AS definition 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);
		res = PQexec(g_conn, query);
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
			fprintf(stderr, "dumpRules(): SELECT failed for table %s\n",
					tblinfo[t].relname);
			exit_nicely(g_conn);
		}

		nrules = PQntuples(res);
		i_definition = PQfnumber(res, "definition");

		/*
		 * Dump them out
		 */
		for (i = 0; i < nrules; i++)
		{
			fprintf(fout, "%s\n", PQgetvalue(res, i, i_definition));
		}

		PQclear(res);

		res = PQexec(g_conn, "end");
		PQclear(res);
	}
}


3338 3339 3340 3341 3342 3343
/* 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).
 */

3344 3345
static void
becomeUser(FILE *fout, const char *username)
3346 3347 3348
{
	static const char *lastusername = "";

3349
	if (!aclsOption)
3350 3351 3352 3353 3354 3355 3356 3357 3358
		return;

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

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

	lastusername = username;
}