pg_dump.c 69.3 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.79 1998/08/06 05:12:51 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>
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
#include "pg_dump.h"

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

V
Vadim B. Mikheev 已提交
95 96
static char *AddAcl(char *s, const char *add);
static char *GetPrivledges(char *s);
97
static ACL *ParseACL(const char *acls, int *count);
98
static void becomeUser(FILE *fout, const char *username);
V
Vadim B. Mikheev 已提交
99

100 101 102
extern char *optarg;
extern int	optind,
			opterr;
103 104

/* global decls */
105
bool		g_verbose;			/* User wants verbose narration of our
106
								 * activities. */
107 108 109 110 111 112 113
int			g_last_builtin_oid; /* value of the last builtin oid */
FILE	   *g_fout;				/* the script file */
PGconn	   *g_conn;				/* the database connection */
int			dumpData;			/* dump data using proper insert strings */
int			attrNames;			/* put attr names into insert strings */
int			schemaOnly;
int			dataOnly;
114
int			aclsOption;
115

116
char		g_opaque_type[10];	/* name for the opaque type */
117 118

/* placeholders for the delimiters for comments */
119 120
char		g_comment_start[10];
char		g_comment_end[10];
121 122 123


static void
124
usage(const char *progname)
125
{
126
	fprintf(stderr,
127
			"usage:  %s [options] dbname\n", progname);
128
	fprintf(stderr,
129
			"\t -a          \t\t dump out only the data, no schema\n");
130
	fprintf(stderr,
131
			"\t -d          \t\t dump data as proper insert strings\n");
132
	fprintf(stderr,
133
			"\t -D          \t\t dump data as inserts with attribute names\n");
134
	fprintf(stderr,
135
			"\t -f filename \t\t script output filename\n");
136
	fprintf(stderr,
137
			"\t -h hostname \t\t server host name\n");
138
	fprintf(stderr,
139
			"\t -o          \t\t dump object id's (oids)\n");
140
	fprintf(stderr,
141
			"\t -p port     \t\t server port number\n");
142
	fprintf(stderr,
143
			"\t -s          \t\t dump out only the schema, no data\n");
144 145
	fprintf(stderr,
			"\t -t table    \t\t dump for this table only\n");
146 147
	fprintf(stderr,
			"\t -u          \t\t use password authentication\n");
148
	fprintf(stderr,
149
			"\t -v          \t\t verbose\n");
150 151 152 153 154 155 156 157
	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);
158 159
}

160
static void
161
exit_nicely(PGconn *conn)
162
{
163 164
	PQfinish(conn);
	exit(1);
165 166 167
}


M
Marc G. Fournier 已提交
168 169
/*
 * isViewRule
170
 *				Determine if the relation is a VIEW
M
Marc G. Fournier 已提交
171 172
 *
 */
173
static bool
M
Marc G. Fournier 已提交
174 175
isViewRule(char *relname)
{
176 177 178
	PGresult   *res;
	int			ntups;
	char		query[MAXQUERYLEN];
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

	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 "
			"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 已提交
207
}
208

209 210 211 212
#define COPYBUFSIZ		8192


static void
213
dumpClasses_nodumpData(FILE *fout, const char *classname, const bool oids)
214 215
{

216 217 218 219 220
	PGresult   *res;
	char		query[255];
	int			ret;
	bool		copydone;
	char		copybuf[COPYBUFSIZ];
221 222 223

	if (oids)
	{
224
		fprintf(fout, "COPY \"%s\" WITH OIDS FROM stdin;\n",
225
				fmtId(classname));
226
		sprintf(query, "COPY \"%s\" WITH OIDS TO stdout;\n",
227
				fmtId(classname));
228 229 230
	}
	else
	{
231 232
		fprintf(fout, "COPY \"%s\" FROM stdin;\n", fmtId(classname));
		sprintf(query, "COPY \"%s\" TO stdout;\n", fmtId(classname));
233 234
	}
	res = PQexec(g_conn, query);
235 236
	if (!res ||
		PQresultStatus(res) == PGRES_FATAL_ERROR)
237
	{
238
		fprintf(stderr, "SQL query to dump the contents of Table '%s' "
239 240 241 242 243 244 245 246 247
				"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)
		{
248
			fprintf(stderr, "SQL query to dump the contents of Table '%s' "
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
					"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)
			{
				ret = PQgetline(res->conn, copybuf, COPYBUFSIZ);

				if (copybuf[0] == '\\' &&
					copybuf[1] == '.' &&
					copybuf[2] == '\0')
				{
					copydone = true;	/* don't print this... */
				}
				else
				{
					fputs(copybuf, fout);
					switch (ret)
					{
273 274 275 276 277 278 279 280
						case EOF:
							copydone = true;
							/* FALLTHROUGH */
						case 0:
							fputc('\n', fout);
							break;
						case 1:
							break;
281 282 283 284 285 286 287 288
					}
				}
			}
			fprintf(fout, "\\.\n");
		}
		ret = PQendcopy(res->conn);
		if (ret != 0)
		{
289
			fprintf(stderr, "SQL query to dump the contents of Table '%s' "
290 291 292 293 294 295 296 297 298 299 300 301
					"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);
	}
302 303 304 305 306
}



static void
307
dumpClasses_dumpData(FILE *fout, const char *classname,
308 309 310
					 const TableInfo tblinfo, bool oids)
{

311 312 313 314 315 316 317
	PGresult   *res;
	char		query[255];
	int			actual_atts;	/* number of attrs in this a table */
	char		expandbuf[COPYBUFSIZ];
	char		q[MAXQUERYLEN];
	int			tuple;
	int			field;
318

319
	sprintf(query, "SELECT * FROM \"%s\"", classname);
320 321 322 323 324 325 326 327 328 329
	res = PQexec(g_conn, query);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, "dumpClasses(): command failed\n");
		exit_nicely(g_conn);
	}
	tuple = 0;
	while (tuple < PQntuples(res))
	{
330
		fprintf(fout, "INSERT INTO \"%s\" ", fmtId(classname));
331 332
		if (attrNames)
		{
333
			int			j;
334 335 336 337 338 339 340

			actual_atts = 0;
			sprintf(q, "(");
			for (j = 0; j < tblinfo.numatts; j++)
			{
				if (tblinfo.inhAttrs[j] == 0)
				{
341
					sprintf(q, "%s%s\"%s\"",
342 343
							q,
							(actual_atts > 0) ? "," : "",
344
							fmtId(tblinfo.attnames[j]));
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
					actual_atts++;
				}
			}
			sprintf(q, "%s%s", q, ") ");
			fprintf(fout, q);
		}
		fprintf(fout, "values (");
		field = 0;
		do
		{
			if (PQgetisnull(res, tuple, field))
				fprintf(fout, "NULL");
			else
			{
				switch (PQftype(res, field))
				{
361 362 363 364 365 366 367 368 369 370 371
					case INT2OID:
					case INT4OID:
					case OIDOID:		/* int types */
					case FLOAT4OID:
					case FLOAT8OID:		/* float types */
						fprintf(fout, "%s",
								PQgetvalue(res, tuple, field));
						break;
					default:
						{
							char	   *expsrc,
372 373
									   *expdest;

374 375 376 377 378 379 380 381 382
							/*
							 * Before outputting string value, expand all
							 * single quotes to twin single quotes - dhb -
							 * 6/11/96
							 */
							expsrc = PQgetvalue(res, tuple, field);
							expdest = expandbuf;
							while (*expsrc)
							{
383
								*expdest++ = *expsrc;
384 385 386 387 388
								if (*expsrc == (char) 0x27)		/* single quote */
									*expdest++ = *expsrc;
								expsrc++;
							}
							*expdest = *expsrc; /* null term. */
389

390 391 392
							fprintf(fout, "'%s'", expandbuf);
						}
						break;
393 394 395 396 397 398 399 400 401 402
				}
			}
			field++;
			if (field != PQnfields(res))
				fprintf(fout, ",");
		} while (field < PQnfields(res));
		fprintf(fout, ");\n");
		tuple++;
	}
	PQclear(res);
403 404 405 406 407 408
}



/*
 * DumpClasses -
409
 *	  dump the contents of all the classes.
410 411
 */
static void
412
dumpClasses(const TableInfo tblinfo[], const int numTables, FILE *fout,
413 414 415
			const char *onlytable, const bool oids)
{

416 417
	int			i;
	char	   *all_only;
418 419 420 421 422 423 424 425 426

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

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

	for (i = 0; i < numTables; i++)
	{
448
		const char *classname = tblinfo[i].relname;
449 450 451 452

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

		if (tblinfo[i].sequence)/* already dumped */
V
Vadim B. Mikheev 已提交
455
			continue;
456 457 458 459

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

463 464
			becomeUser(fout, tblinfo[i].usename);

465 466 467 468
			if (!dumpData)
				dumpClasses_nodumpData(fout, classname, oids);
			else
				dumpClasses_dumpData(fout, classname, tblinfo[i], oids);
469
		}
470
	}
471 472 473
}


474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
static void
prompt_for_password(char *username, char *password)
{
	int			length;

#ifdef HAVE_TERMIOS_H
	struct termios t_orig,
				t;

#endif

	printf("Username: ");
	fgets(username, 9, stdin);
	length = strlen(username);
	/* skip rest of the line */
	if (length > 0 && username[length - 1] != '\n')
	{
		static char buf[512];

		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
	fgets(password, 9, stdin);
#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')
	{
		static char buf[512];

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

530

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

	g_verbose = false;

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

556
	dataOnly = schemaOnly = dumpData = attrNames = 0;
557 558 559

	progname = *argv;

560
	while ((c = getopt(argc, argv, "adDf:h:op:st:vzu")) != EOF)
561 562 563
	{
		switch (c)
		{
564 565 566 567 568 569 570 571 572 573 574
			case 'a':			/* Dump data only */
				dataOnly = 1;
				break;
			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;
575 576 577
			case 'f':			/* output file name */
				filename = optarg;
				break;
B
Bruce Momjian 已提交
578
			case 'h':			/* server host */
579 580
				pghost = optarg;
				break;
581 582 583
			case 'o':			/* Dump oids */
				oids = 1;
				break;
584 585 586
			case 'p':			/* server port */
				pgport = optarg;
				break;
587
			case 's':			/* dump schema only */
588 589 590
				schemaOnly = 1;
				break;
			case 't':			/* Dump data for this table only */
591
				{
592
					int			i;
593 594 595

					tablename = strdup(optarg);
					for (i = 0; tablename[i]; i++)
596 597
						if (isascii((unsigned char)tablename[i]) &&
						    isupper(tablename[i]))
598 599
							tablename[i] = tolower(tablename[i]);
				}
600
				break;
601 602
			case 'v':			/* verbose */
				g_verbose = true;
603
				break;
604 605
			case 'z':			/* Dump ACLs and table ownership info */
				aclsOption = 1;
606
				break;
607 608 609
			case 'u':
				use_password = 1;
				break;
610 611 612
			default:
				usage(progname);
				break;
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
		}
	}

	/* open the output file */
	if (filename == NULL)
		g_fout = stdout;
	else
	{
		g_fout = fopen(filename, "w");
		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);
	}

639 640 641 642 643
	/* g_conn = PQsetdb(pghost, pgport, NULL, NULL, dbname); */
	if (pghost != NULL)
	{
		sprintf(tmp_string, "host=%s ", pghost);
		strcat(connect_string, tmp_string);
644
	}
645 646 647 648
	if (pgport != NULL)
	{
		sprintf(tmp_string, "port=%s ", pgport);
		strcat(connect_string, tmp_string);
649
	}
650 651 652 653
	if (dbname != NULL)
	{
		sprintf(tmp_string, "dbname=%s ", dbname);
		strcat(connect_string, tmp_string);
654
	}
655 656 657 658 659 660 661 662
	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);
663 664
		MemSet(tmp_string, 0, sizeof(tmp_string));
		MemSet(password, 0, sizeof(password));
665 666
	}
	g_conn = PQconnectdb(connect_string);
667
	MemSet(connect_string, 0, sizeof(connect_string));
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
	/* 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)
			fprintf(stderr, "%s last builtin oid is %d %s\n",
					g_comment_start, g_last_builtin_oid, g_comment_end);
685
		tblinfo = dumpSchema(g_fout, &numTables, tablename, aclsOption);
686 687
	}
	else
688
		tblinfo = dumpSchema(NULL, &numTables, tablename, aclsOption);
689 690 691 692

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

693 694
	if (!dataOnly)				/* dump indexes and triggers at the end
								 * for performance */
V
Vadim B. Mikheev 已提交
695 696 697 698
	{
		dumpSchemaIdx(g_fout, tablename, tblinfo, numTables);
		dumpTriggers(g_fout, tablename, tblinfo, numTables);
	}
699 700 701 702 703 704

	fflush(g_fout);
	fclose(g_fout);
	clearTableInfo(tblinfo, numTables);
	PQfinish(g_conn);
	exit(0);
705 706 707
}

/*
708 709
 * getTypes:
 *	  read all base types in the system catalogs and return them in the
710 711
 * TypeInfo* structure
 *
712
 *	numTypes is set to the number of types read in
713 714
 *
 */
715
TypeInfo   *
716 717
getTypes(int *numTypes)
{
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
	PGresult   *res;
	int			ntups;
	int			i;
	char		query[MAXQUERYLEN];
	TypeInfo   *tinfo;

	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;
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 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

	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;
833 834 835 836
}

/*
 * getOperators:
837
 *	  read all operators in the system catalogs and return them in the
838 839
 * OprInfo* structure
 *
840 841
 *	numOprs is set to the number of operators read in
 *
842 843
 *
 */
844
OprInfo    *
845 846
getOperators(int *numOprs)
{
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
	PGresult   *res;
	int			ntups;
	int			i;
	char		query[MAXQUERYLEN];

	OprInfo    *oprinfo;

	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;
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 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

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

941
void
942
clearTypeInfo(TypeInfo *tp, int numTypes)
943
{
944
	int			i;
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977

	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);
978 979 980
}

void
981
clearFuncInfo(FuncInfo *fun, int numFuncs)
982
{
983 984
	int			i,
				a;
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006

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

1009
static void
1010
clearTableInfo(TableInfo *tblinfo, int numTables)
1011
{
1012 1013
	int			i,
				j;
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038

	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]);
		}
1039 1040
		if (tblinfo[i].atttypmod)
			free((int *) tblinfo[i].atttypmod);
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
		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);
1052 1053
}

1054
void
1055
clearInhInfo(InhInfo *inh, int numInherits)
1056
{
1057
	int			i;
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068

	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);
1069 1070 1071
}

void
1072
clearOprInfo(OprInfo *opr, int numOprs)
1073
{
1074
	int			i;
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109

	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);
1110 1111 1112
}

void
1113
clearIndInfo(IndInfo *ind, int numIndices)
1114
{
1115 1116
	int			i,
				a;
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140

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

void
B
Bruce Momjian 已提交
1144
clearAggInfo(AggInfo *agginfo, int numArgs)
1145
{
1146
	int			i;
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175

	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);
1176
}
1177 1178 1179

/*
 * getAggregates:
1180
 *	  read all the user-defined aggregates in the system catalogs and
1181 1182
 * return them in the AggInfo* structure
 *
1183 1184
 * numAggs is set to the number of aggregates read in
 *
1185 1186
 *
 */
1187
AggInfo    *
1188 1189
getAggregates(int *numAggs)
{
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
	PGresult   *res;
	int			ntups;
	int			i;
	char		query[MAXQUERYLEN];
	AggInfo    *agginfo;

	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;
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 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

	/* 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;
1270 1271 1272 1273
}

/*
 * getFuncs:
1274
 *	  read all the user-defined functions in the system catalogs and
1275 1276
 * return them in the FuncInfo* structure
 *
1277 1278
 * numFuncs is set to the number of functions read in
 *
1279 1280
 *
 */
1281
FuncInfo   *
1282 1283
getFuncs(int *numFuncs)
{
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
	PGresult   *res;
	int			ntups;
	int			i;
	char		query[MAXQUERYLEN];
	FuncInfo   *finfo;

	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;
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354

	/* 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 "
			"where pg_proc.oid > '%d'::oid and proowner = usesysid",
			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));
1355
		finfo[i].lang = atoi(PQgetvalue(res, i, i_prolang));
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368

		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;
1369 1370 1371 1372 1373

}

/*
 * getTables
1374
 *	  read all the user-defined tables (no indices, no catalogs)
1375 1376
 * in the system catalogs return them in the TableInfo* structure
 *
1377 1378
 * numTables is set to the number of tables read in
 *
1379 1380
 *
 */
1381
TableInfo  *
V
Vadim B. Mikheev 已提交
1382
getTables(int *numTables, FuncInfo *finfo, int numFuncs)
1383
{
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
	PGresult   *res;
	int			ntups;
	int			i;
	char		query[MAXQUERYLEN];
	TableInfo  *tblinfo;

	int			i_oid;
	int			i_relname;
	int			i_relkind;
	int			i_relacl;
	int			i_usename;
V
Vadim B. Mikheev 已提交
1395 1396
	int			i_relchecks;
	int			i_reltriggers;
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415

	/*
	 * 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,
1416 1417
			"SELECT pg_class.oid, relname, relkind, relacl, usename, "
			"relchecks, reltriggers "
1418 1419 1420
			"from pg_class, pg_user "
			"where relowner = usesysid and "
			"(relkind = 'r' or relkind = 'S') and relname !~ '^pg_' "
1421
			"order by oid");
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441

	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 已提交
1442 1443
	i_relchecks = PQfnumber(res, "relchecks");
	i_reltriggers = PQfnumber(res, "reltriggers");
1444 1445 1446 1447 1448 1449 1450 1451

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

V
Vadim B. Mikheev 已提交
1455 1456 1457 1458
		/* Get CHECK constraints */
		if (tblinfo[i].ncheck > 0)
		{
			PGresult   *res2;
1459 1460
			int			i_rcname,
						i_rcsrc;
V
Vadim B. Mikheev 已提交
1461 1462
			int			ntups2;
			int			i2;
1463

V
Vadim B. Mikheev 已提交
1464
			if (g_verbose)
1465
				fprintf(stderr, "%s finding CHECK constraints for relation: '%s' %s\n",
V
Vadim B. Mikheev 已提交
1466 1467 1468
						g_comment_start,
						tblinfo[i].relname,
						g_comment_end);
1469

V
Vadim B. Mikheev 已提交
1470 1471 1472 1473 1474
			sprintf(query, "SELECT rcname, rcsrc from pg_relcheck "
					"where rcrelid = '%s'::oid ",
					tblinfo[i].oid);
			res2 = PQexec(g_conn, query);
			if (!res2 ||
1475
				PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
1476 1477 1478 1479 1480 1481 1482
			{
				fprintf(stderr, "getTables(): SELECT (for CHECK) failed\n");
				exit_nicely(g_conn);
			}
			ntups2 = PQntuples(res2);
			if (ntups2 != tblinfo[i].ncheck)
			{
1483
				fprintf(stderr, "getTables(): relation '%s': %d CHECKs were expected, but got %d\n",
1484
						tblinfo[i].relname, tblinfo[i].ncheck, ntups2);
V
Vadim B. Mikheev 已提交
1485 1486 1487 1488
				exit_nicely(g_conn);
			}
			i_rcname = PQfnumber(res2, "rcname");
			i_rcsrc = PQfnumber(res2, "rcsrc");
1489
			tblinfo[i].check_expr = (char **) malloc(ntups2 * sizeof(char *));
V
Vadim B. Mikheev 已提交
1490 1491
			for (i2 = 0; i2 < ntups2; i2++)
			{
1492 1493 1494
				char	   *name = PQgetvalue(res2, i2, i_rcname);
				char	   *expr = PQgetvalue(res2, i2, i_rcsrc);

V
Vadim B. Mikheev 已提交
1495
				query[0] = 0;
1496 1497
				if (name[0] != '$')
					sprintf(query, "CONSTRAINT %s ", name);
1498
				sprintf(query, "%sCHECK (%s)", query, expr);
1499
				tblinfo[i].check_expr[i2] = strdup(query);
V
Vadim B. Mikheev 已提交
1500 1501 1502 1503 1504
			}
			PQclear(res2);
		}
		else
			tblinfo[i].check_expr = NULL;
1505

V
Vadim B. Mikheev 已提交
1506 1507 1508 1509
		/* Get Triggers */
		if (tblinfo[i].ntrig > 0)
		{
			PGresult   *res2;
1510 1511 1512 1513 1514
			int			i_tgname,
						i_tgfoid,
						i_tgtype,
						i_tgnargs,
						i_tgargs;
V
Vadim B. Mikheev 已提交
1515 1516
			int			ntups2;
			int			i2;
1517

V
Vadim B. Mikheev 已提交
1518
			if (g_verbose)
1519
				fprintf(stderr, "%s finding Triggers for relation: '%s' %s\n",
V
Vadim B. Mikheev 已提交
1520 1521 1522
						g_comment_start,
						tblinfo[i].relname,
						g_comment_end);
1523

V
Vadim B. Mikheev 已提交
1524 1525 1526 1527 1528 1529
			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 ||
1530
				PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
1531 1532 1533 1534 1535 1536 1537
			{
				fprintf(stderr, "getTables(): SELECT (for TRIGGER) failed\n");
				exit_nicely(g_conn);
			}
			ntups2 = PQntuples(res2);
			if (ntups2 != tblinfo[i].ntrig)
			{
1538
				fprintf(stderr, "getTables(): relation '%s': %d Triggers were expected, but got %d\n",
1539
						tblinfo[i].relname, tblinfo[i].ntrig, ntups2);
V
Vadim B. Mikheev 已提交
1540 1541 1542 1543 1544 1545 1546
				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");
1547
			tblinfo[i].triggers = (char **) malloc(ntups2 * sizeof(char *));
V
Vadim B. Mikheev 已提交
1548 1549
			for (i2 = 0, query[0] = 0; i2 < ntups2; i2++)
			{
1550 1551 1552 1553 1554 1555 1556 1557
				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 已提交
1558 1559 1560
				for (findx = 0; findx < numFuncs; findx++)
				{
					if (strcmp(finfo[findx].oid, tgfunc) == 0 &&
1561 1562
						finfo[findx].lang == ClanguageId &&
						finfo[findx].nargs == 0 &&
V
Vadim B. Mikheev 已提交
1563 1564 1565 1566 1567
						strcmp(finfo[findx].prorettype, "0") == 0)
						break;
				}
				if (findx == numFuncs)
				{
1568
					fprintf(stderr, "getTables(): relation '%s': cannot find function with oid %s for trigger %s\n",
1569
							tblinfo[i].relname, tgfunc, PQgetvalue(res2, i2, i_tgname));
V
Vadim B. Mikheev 已提交
1570 1571 1572
					exit_nicely(g_conn);
				}
				tgfunc = finfo[findx].proname;
1573
				sprintf(query, "CREATE TRIGGER \"%s\" ", PQgetvalue(res2, i2, i_tgname));
V
Vadim B. Mikheev 已提交
1574 1575 1576
				/* Trigger type */
				findx = 0;
				if (TRIGGER_FOR_BEFORE(tgtype))
1577
					strcat(query, "BEFORE");
V
Vadim B. Mikheev 已提交
1578
				else
1579
					strcat(query, "AFTER");
V
Vadim B. Mikheev 已提交
1580 1581
				if (TRIGGER_FOR_INSERT(tgtype))
				{
1582
					strcat(query, " INSERT");
V
Vadim B. Mikheev 已提交
1583 1584 1585 1586 1587
					findx++;
				}
				if (TRIGGER_FOR_DELETE(tgtype))
				{
					if (findx > 0)
1588
						strcat(query, " OR DELETE");
V
Vadim B. Mikheev 已提交
1589
					else
1590
						strcat(query, " DELETE");
V
Vadim B. Mikheev 已提交
1591 1592 1593
					findx++;
				}
				if (TRIGGER_FOR_UPDATE(tgtype))
1594
				{
V
Vadim B. Mikheev 已提交
1595
					if (findx > 0)
1596
						strcat(query, " OR UPDATE");
V
Vadim B. Mikheev 已提交
1597
					else
1598
						strcat(query, " UPDATE");
1599
				}
1600
				sprintf(query, "%s ON \"%s\" FOR EACH ROW EXECUTE PROCEDURE %s (",
1601
						query, tblinfo[i].relname, tgfunc);
V
Vadim B. Mikheev 已提交
1602 1603
				for (findx = 0; findx < tgnargs; findx++)
				{
1604 1605 1606 1607
					char	   *s,
							   *d;

					for (p = tgargs;;)
V
Vadim B. Mikheev 已提交
1608
					{
1609
						p = strchr(p, '\\');
V
Vadim B. Mikheev 已提交
1610 1611
						if (p == NULL)
						{
1612
							fprintf(stderr, "getTables(): relation '%s': bad argument string (%s) for trigger '%s'\n",
1613 1614 1615
									tblinfo[i].relname,
									PQgetvalue(res2, i2, i_tgargs),
									PQgetvalue(res2, i2, i_tgname));
V
Vadim B. Mikheev 已提交
1616 1617 1618 1619 1620 1621 1622 1623
							exit_nicely(g_conn);
						}
						p++;
						if (*p == '\\')
						{
							p++;
							continue;
						}
1624
						if (p[0] == '0' && p[1] == '0' && p[2] == '0')
V
Vadim B. Mikheev 已提交
1625 1626 1627
							break;
					}
					p--;
1628
					for (s = tgargs, d = &(farg[0]); s < p;)
V
Vadim B. Mikheev 已提交
1629 1630 1631 1632 1633 1634
					{
						if (*s == '\'')
							*d++ = '\\';
						*d++ = *s++;
					}
					*d = 0;
1635 1636
					sprintf(query, "%s'%s'%s", query, farg,
							(findx < tgnargs - 1) ? ", " : "");
V
Vadim B. Mikheev 已提交
1637 1638
					tgargs = p + 4;
				}
1639 1640
				strcat(query, ");\n");
				tblinfo[i].triggers[i2] = strdup(query);
V
Vadim B. Mikheev 已提交
1641 1642 1643 1644 1645
			}
			PQclear(res2);
		}
		else
			tblinfo[i].triggers = NULL;
1646 1647 1648 1649 1650 1651 1652
	}

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

	return tblinfo;
1653 1654 1655 1656 1657

}

/*
 * getInherits
1658
 *	  read all the inheritance information
1659 1660
 * from the system catalogs return them in the InhInfo* structure
 *
1661 1662
 * numInherits is set to the number of tables read in
 *
1663 1664
 *
 */
1665
InhInfo    *
1666 1667
getInherits(int *numInherits)
{
1668 1669 1670 1671 1672
	PGresult   *res;
	int			ntups;
	int			i;
	char		query[MAXQUERYLEN];
	InhInfo    *inhinfo;
1673

1674 1675
	int			i_inhrel;
	int			i_inhparent;
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715

	/* 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;
1716 1717 1718 1719
}

/*
 * getTableAttrs -
1720 1721
 *	  for each table in tblinfo, read its attributes types and names
 *
1722
 * this is implemented in a very inefficient way right now, looping
1723
 * through the tblinfo and doing a join per table to find the attrs and their
1724 1725
 * types
 *
1726
 *	modifies tblinfo
1727 1728
 */
void
1729
getTableAttrs(TableInfo *tblinfo, int numTables)
1730
{
1731 1732 1733 1734 1735
	int			i,
				j;
	char		q[MAXQUERYLEN];
	int			i_attname;
	int			i_typname;
1736
	int			i_atttypmod;
1737
	int			i_attnotnull;
V
Vadim B. Mikheev 已提交
1738
	int			i_atthasdef;
1739 1740
	PGresult   *res;
	int			ntups;
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755

	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)
1756
			fprintf(stderr, "%s finding the attrs and types for table: '%s' %s\n",
1757 1758 1759 1760
					g_comment_start,
					tblinfo[i].relname,
					g_comment_end);

1761
		sprintf(q, "SELECT a.attnum, a.attname, t.typname, a.atttypmod, "
V
Vadim B. Mikheev 已提交
1762
				"a.attnotnull, a.atthasdef "
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
				"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");
1779
		i_atttypmod = PQfnumber(res, "atttypmod");
1780
		i_attnotnull = PQfnumber(res, "attnotnull");
V
Vadim B. Mikheev 已提交
1781
		i_atthasdef = PQfnumber(res, "atthasdef");
1782 1783 1784 1785

		tblinfo[i].numatts = ntups;
		tblinfo[i].attnames = (char **) malloc(ntups * sizeof(char *));
		tblinfo[i].typnames = (char **) malloc(ntups * sizeof(char *));
1786
		tblinfo[i].atttypmod = (int *) malloc(ntups * sizeof(int));
1787 1788
		tblinfo[i].inhAttrs = (int *) malloc(ntups * sizeof(int));
		tblinfo[i].notnull = (bool *) malloc(ntups * sizeof(bool));
V
Vadim B. Mikheev 已提交
1789
		tblinfo[i].adef_expr = (char **) malloc(ntups * sizeof(char *));
1790 1791 1792 1793 1794 1795
		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));
1796
			tblinfo[i].atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
1797 1798 1799
			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 已提交
1800 1801 1802
			if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
			{
				PGresult   *res2;
1803

V
Vadim B. Mikheev 已提交
1804
				if (g_verbose)
1805
					fprintf(stderr, "%s finding DEFAULT expression for attr: '%s' %s\n",
V
Vadim B. Mikheev 已提交
1806 1807 1808
							g_comment_start,
							tblinfo[i].attnames[j],
							g_comment_end);
1809

V
Vadim B. Mikheev 已提交
1810 1811 1812 1813 1814
				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 ||
1815
					PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
1816 1817 1818 1819 1820 1821 1822 1823 1824
				{
					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;
1825 1826 1827
		}
		PQclear(res);
	}
1828 1829 1830 1831 1832
}


/*
 * getIndices
1833
 *	  read all the user-defined indices information
1834 1835
 * from the system catalogs return them in the InhInfo* structure
 *
1836 1837
 * numIndices is set to the number of indices read in
 *
1838 1839
 *
 */
1840
IndInfo    *
1841 1842
getIndices(int *numIndices)
{
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
	int			i;
	char		query[MAXQUERYLEN];
	PGresult   *res;
	int			ntups;
	IndInfo    *indinfo;

	int			i_indexrelname;
	int			i_indrelname;
	int			i_indamname;
	int			i_indproc;
	int			i_indkey;
	int			i_indclass;
	int			i_indisunique;
1856 1857 1858 1859 1860

	/*
	 * find all the user-defined indices. We do not handle partial
	 * indices.
	 *
1861
	 * skip 'xinx*' - indices on inversion objects
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
	 *
	 * 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 "
			"and t1.relam = a.oid and i.indexrelid > '%d'::oid "
1882
			"and t2.relname !~ '^pg_' and t1.relkind != 'l'",
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
			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;
1924 1925 1926 1927
}

/*
 * dumpTypes
1928
 *	  writes out to fout the queries to recreate all the user-defined types
1929 1930 1931
 *
 */
void
1932 1933
dumpTypes(FILE *fout, FuncInfo *finfo, int numFuncs,
		  TypeInfo *tinfo, int numTypes)
1934
{
1935 1936 1937
	int			i;
	char		q[MAXQUERYLEN];
	int			funcInd;
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966

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

1967
		becomeUser(fout, tinfo[i].usename);
1968 1969

		sprintf(q,
1970
				"CREATE TYPE \"%s\" "
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
				"( internallength = %s, externallength = %s, input = %s, "
				"output = %s, send = %s, receive = %s, default = '%s'",
				tinfo[i].typname,
				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)
		{
1984
			char	   *elemType;
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997

			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);
	}
1998 1999 2000 2001
}

/*
 * dumpFuncs
2002
 *	  writes out to fout the queries to recreate all the user-defined functions
2003 2004 2005
 *
 */
void
2006 2007
dumpFuncs(FILE *fout, FuncInfo *finfo, int numFuncs,
		  TypeInfo *tinfo, int numTypes)
2008
{
2009
	int			i;
2010 2011 2012

	for (i = 0; i < numFuncs; i++)
		dumpOneFunc(fout, finfo, i, tinfo, numTypes);
2013 2014 2015 2016
}

/*
 * dumpOneFunc:
2017 2018
 *	  dump out only one function,  the index of which is given in the third
 *	argument
2019 2020 2021
 *
 */

2022
static void
2023 2024
dumpOneFunc(FILE *fout, FuncInfo *finfo, int i,
			TypeInfo *tinfo, int numTypes)
2025
{
2026 2027
	char		q[MAXQUERYLEN];
	int			j;
2028 2029 2030 2031 2032 2033

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

2034
	becomeUser(fout, finfo[i].usename);
2035

2036
	sprintf(q, "CREATE FUNCTION \"%s\" (", finfo[i].proname);
2037 2038
	for (j = 0; j < finfo[i].nargs; j++)
	{
2039
		char	   *typname;
2040 2041

		typname = findTypeByOid(tinfo, numTypes, finfo[i].argtypes[j]);
2042
		sprintf(q, "%s%s\"%s\"",
2043 2044
				q,
				(j > 0) ? "," : "",
2045
				fmtId(typname));
2046 2047 2048 2049
	}
	sprintf(q, "%s ) RETURNS %s%s AS '%s' LANGUAGE '%s';\n",
			q,
			(finfo[i].retset) ? " SETOF " : "",
2050
			fmtId(findTypeByOid(tinfo, numTypes, finfo[i].prorettype)),
2051
			(finfo[i].lang == INTERNALlanguageId) ? finfo[i].prosrc :
2052 2053
			(finfo[i].lang == ClanguageId) ? finfo[i].probin :
		  (finfo[i].lang == SQLlanguageId) ? finfo[i].prosrc : "unknown",
2054
			(finfo[i].lang == INTERNALlanguageId) ? "INTERNAL" :
2055 2056
			(finfo[i].lang == ClanguageId) ? "C" :
			(finfo[i].lang == SQLlanguageId) ? "SQL" : "unknown");
2057 2058

	fputs(q, fout);
2059 2060 2061 2062 2063

}

/*
 * dumpOprs
2064
 *	  writes out to fout the queries to recreate all the user-defined operators
2065 2066
 *
 */
2067
void
2068 2069
dumpOprs(FILE *fout, OprInfo *oprinfo, int numOperators,
		 TypeInfo *tinfo, int numTypes)
2070
{
2071 2072 2073 2074 2075 2076
	int			i;
	char		q[MAXQUERYLEN];
	char		leftarg[MAXQUERYLEN];
	char		rightarg[MAXQUERYLEN];
	char		commutator[MAXQUERYLEN];
	char		negator[MAXQUERYLEN];
B
Bruce Momjian 已提交
2077
	char		restrictor[MAXQUERYLEN];
2078 2079
	char		join[MAXQUERYLEN];
	char		sortop[MAXQUERYLEN];
2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105

	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)
		{
			sprintf(leftarg, ", LEFTARG = %s ",
2106
			  fmtId(findTypeByOid(tinfo, numTypes, oprinfo[i].oprleft)));
2107 2108 2109 2110 2111
		}
		if (strcmp(oprinfo[i].oprkind, "l") == 0 ||
			strcmp(oprinfo[i].oprkind, "b") == 0)
		{
			sprintf(rightarg, ", RIGHTARG = %s ",
2112
			 fmtId(findTypeByOid(tinfo, numTypes, oprinfo[i].oprright)));
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
		}
		if (strcmp(oprinfo[i].oprcom, "0") == 0)
			commutator[0] = '\0';
		else
			sprintf(commutator, ", COMMUTATOR = %s ",
				 findOprByOid(oprinfo, numOperators, oprinfo[i].oprcom));

		if (strcmp(oprinfo[i].oprnegate, "0") == 0)
			negator[0] = '\0';
		else
			sprintf(negator, ", NEGATOR = %s ",
			  findOprByOid(oprinfo, numOperators, oprinfo[i].oprnegate));

		if (strcmp(oprinfo[i].oprrest, "-") == 0)
B
Bruce Momjian 已提交
2127
			restrictor[0] = '\0';
2128
		else
B
Bruce Momjian 已提交
2129
			sprintf(restrictor, ", RESTRICT = %s ", oprinfo[i].oprrest);
2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148

		if (strcmp(oprinfo[i].oprjoin, "-") == 0)
			join[0] = '\0';
		else
			sprintf(join, ", JOIN = %s ", oprinfo[i].oprjoin);

		if (strcmp(oprinfo[i].oprlsortop, "0") == 0)
			sortop[0] = '\0';
		else
		{
			sprintf(sortop, ", SORT = %s ",
					findOprByOid(oprinfo, numOperators,
								 oprinfo[i].oprlsortop));
			if (strcmp(oprinfo[i].oprrsortop, "0") != 0)
				sprintf(sortop, "%s , %s", sortop,
						findOprByOid(oprinfo, numOperators,
									 oprinfo[i].oprlsortop));
		}

2149
		becomeUser(fout, oprinfo[i].usename);
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159

		sprintf(q,
				"CREATE OPERATOR %s "
				"(PROCEDURE = %s %s %s %s %s %s %s %s %s);\n ",
				oprinfo[i].oprname,
				oprinfo[i].oprcode,
				leftarg,
				rightarg,
				commutator,
				negator,
B
Bruce Momjian 已提交
2160
				restrictor,
2161
				(strcmp(oprinfo[i].oprcanhash, "t") == 0) ? ", HASHES" : "",
2162 2163 2164 2165 2166
				join,
				sortop);

		fputs(q, fout);
	}
2167 2168 2169 2170
}

/*
 * dumpAggs
2171
 *	  writes out to fout the queries to create all the user-defined aggregates
2172 2173 2174
 *
 */
void
2175 2176
dumpAggs(FILE *fout, AggInfo *agginfo, int numAggs,
		 TypeInfo *tinfo, int numTypes)
2177
{
2178 2179 2180 2181
	int			i;
	char		q[MAXQUERYLEN];
	char		sfunc1[MAXQUERYLEN];
	char		sfunc2[MAXQUERYLEN];
V
Vadim B. Mikheev 已提交
2182
	char		basetype[MAXQUERYLEN];
2183 2184 2185
	char		finalfunc[MAXQUERYLEN];
	char		comma1[2],
				comma2[2];
2186 2187 2188 2189 2190 2191

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

V
Vadim B. Mikheev 已提交
2193 2194
		sprintf(basetype,
				"BASETYPE = %s, ",
2195
		  fmtId(findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype)));
2196 2197 2198 2199 2200 2201

		if (strcmp(agginfo[i].aggtransfn1, "-") == 0)
			sfunc1[0] = '\0';
		else
		{
			sprintf(sfunc1,
V
Vadim B. Mikheev 已提交
2202
					"SFUNC1 = %s, STYPE1 = %s",
2203
					agginfo[i].aggtransfn1,
2204
					fmtId(findTypeByOid(tinfo, numTypes, agginfo[i].aggtranstype1)));
2205
			if (agginfo[i].agginitval1)
V
Vadim B. Mikheev 已提交
2206
				sprintf(sfunc1, "%s, INITCOND1 = '%s'",
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
						sfunc1, agginfo[i].agginitval1);

		}

		if (strcmp(agginfo[i].aggtransfn2, "-") == 0)
			sfunc2[0] = '\0';
		else
		{
			sprintf(sfunc2,
					"SFUNC2 = %s, STYPE2 = %s",
					agginfo[i].aggtransfn2,
2218
					fmtId(findTypeByOid(tinfo, numTypes, agginfo[i].aggtranstype2)));
2219
			if (agginfo[i].agginitval2)
V
Vadim B. Mikheev 已提交
2220
				sprintf(sfunc2, "%s, INITCOND2 = '%s'",
2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243
						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';

2244
		becomeUser(fout, agginfo[i].usename);
2245

V
Vadim B. Mikheev 已提交
2246
		sprintf(q, "CREATE AGGREGATE %s ( %s %s%s %s%s %s );\n",
2247
				agginfo[i].aggname,
V
Vadim B. Mikheev 已提交
2248
				basetype,
2249 2250 2251 2252 2253 2254 2255 2256
				sfunc1,
				comma1,
				sfunc2,
				comma2,
				finalfunc);

		fputs(q, fout);
	}
2257 2258
}

2259 2260 2261 2262 2263 2264 2265 2266
/*
 * These are some support functions to fix the acl problem of pg_dump
 *
 * Matthew C. Aycock 12/02/97
 */
/*
 * This will return a new string: "s,add"
 */
V
Vadim B. Mikheev 已提交
2267 2268
static char *
AddAcl(char *s, const char *add)
2269
{
2270
	char	   *t;
2271

2272
	if (s == (char *) NULL)
2273 2274
		return (strdup(add));

2275 2276
	t = (char *) calloc((strlen(s) + strlen(add) + 1), sizeof(char));
	sprintf(t, "%s,%s", s, add);
2277

2278
	return (t);
2279
}
2280

2281 2282 2283 2284
/*
 * This will take a string of 'arwR' and return a
 * comma delimited string of SELECT,INSERT,UPDATE,DELETE,RULE
 */
V
Vadim B. Mikheev 已提交
2285 2286
static char *
GetPrivledges(char *s)
2287
{
2288
	char	   *acls = NULL;
2289

B
Bruce Momjian 已提交
2290 2291 2292 2293 2294
	/* Grant All     == arwR */
	/* INSERT        == a   */
	/* UPDATE/DELETE == w   */
	/* SELECT        == r   */
	/* RULE          == R   */
2295

2296 2297
	if (strstr(s, "arwR"))
		return (strdup("ALL"));
2298

B
Bruce Momjian 已提交
2299
	if (strchr(s, 'a'))
2300
		acls = AddAcl(acls, "INSERT");
2301

B
Bruce Momjian 已提交
2302
	if (strchr(s, 'w'))
2303
		acls = AddAcl(acls, "UPDATE,DELETE");
B
Bruce Momjian 已提交
2304 2305

	if (strchr(s, 'r'))
2306
		acls = AddAcl(acls, "SELECT");
2307

2308 2309
	if (strchr(s, 'R'))
		acls = AddAcl(acls, "RULES");
2310

2311
	return (acls);
2312
}
2313

2314 2315
/* This will parse the acl string of TableInfo
 * into a two deminsional aray:
2316
 *	  user | Privledges
2317 2318 2319
 * So to reset the acls I need to grant these priviledges
 * to user
 */
V
Vadim B. Mikheev 已提交
2320
static ACL *
2321
ParseACL(const char *acls, int *count)
2322
{
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337
	ACL		   *ParsedAcl = NULL;
	int			i,
				len,
				NumAcls = 1,	/* There is always public */
				AclLen = 0;
	char	   *s = NULL,
			   *user = NULL,
			   *priv = NULL,
			   *tok;

	AclLen = strlen(acls);

	if (AclLen == 0)
	{
		*count = 0;
2338 2339 2340
		return (ACL *) NULL;
	}

2341
	for (i = 0; i < AclLen; i++)
2342 2343 2344
		if (acls[i] == ',')
			NumAcls++;

2345 2346 2347 2348
	ParsedAcl = (ACL *) calloc(AclLen, sizeof(ACL));
	if (!ParsedAcl)
	{
		fprintf(stderr, "Could not allocate space for ACLS!\n");
2349
		exit_nicely(g_conn);
2350 2351
	}

2352 2353 2354
	s = strdup(acls);

	/* Setup up public */
2355
	ParsedAcl[0].user = NULL;	/* indicates PUBLIC */
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371
	tok = strtok(s, ",");
	ParsedAcl[0].privledges = GetPrivledges(strchr(tok, '='));

	/* Do the rest of the users */
	i = 1;
	while ((i < NumAcls) && ((tok = strtok(NULL, ",")) != (char *) NULL))
	{
		/* User name is string up to = in tok */
		len = strchr(tok, '=') - tok - 1;
		user = (char *) calloc(len + 1, sizeof(char));
		strncpy(user, tok + 1, len);
		if (user[len - 1] == '\"')
			user[len - 1] = (char) NULL;
		priv = GetPrivledges(tok + len + 2);
		ParsedAcl[i].user = user;
		ParsedAcl[i].privledges = priv;
2372 2373 2374
		i++;
	}

2375
	*count = NumAcls;
2376 2377
	return (ParsedAcl);
}
B
Bruce Momjian 已提交
2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395
/*
 * dumpACL:
 *    Write out grant/revoke information
 *    Called for sequences and tables
 */

void
dumpACL(FILE *fout, TableInfo tbinfo)
{
	int k, l;
	ACL		   *ACLlist;

	ACLlist = ParseACL(tbinfo.relacl, &l);
	if (ACLlist == (ACL *) NULL)
		if (l == 0)
			return;
		else
		{
2396
			fprintf(stderr, "Could not parse ACL list for '%s'...Exiting!\n",
B
Bruce Momjian 已提交
2397 2398 2399 2400 2401 2402
					tbinfo.relname);
			exit_nicely(g_conn);
		}

	/* Revoke Default permissions for PUBLIC */
	fprintf(fout,
2403
			"REVOKE ALL on \"%s\" from PUBLIC;\n",
B
Bruce Momjian 已提交
2404 2405 2406 2407 2408
			tbinfo.relname);

	for (k = 0; k < l; k++)
	{
		if (ACLlist[k].privledges != (char *) NULL)
2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
		{
			if (ACLlist[k].user == (char *) NULL)
				fprintf(fout,
						"GRANT %s on \"%s\" to PUBLIC;\n",
						ACLlist[k].privledges, tbinfo.relname);
			else
				fprintf(fout,
						"GRANT %s on \"%s\" to \"%s\";\n",
						ACLlist[k].privledges, tbinfo.relname,
						ACLlist[k].user);
		}
B
Bruce Momjian 已提交
2420 2421 2422
	}
}

2423

2424 2425
/*
 * dumpTables:
2426
 *	  write out to fout all the user-define tables
2427
 */
2428

2429
void
2430 2431 2432
dumpTables(FILE *fout, TableInfo *tblinfo, int numTables,
		   InhInfo *inhinfo, int numInherits,
		   TypeInfo *tinfo, int numTypes, const char *tablename,
2433
		   const bool acls)
2434
{
2435 2436
	int			i,
				j,
B
Bruce Momjian 已提交
2437
				k;
2438 2439 2440 2441
	char		q[MAXQUERYLEN];
	char	  **parentRels;		/* list of names of parent relations */
	int			numParents;
	int			actual_atts;	/* number of attrs in this CREATE statment */
2442

V
Vadim B. Mikheev 已提交
2443 2444 2445 2446 2447 2448 2449
	/* First - dump SEQUENCEs */
	for (i = 0; i < numTables; i++)
	{
		if (!(tblinfo[i].sequence))
			continue;
		if (!tablename || (!strcmp(tblinfo[i].relname, tablename)))
		{
2450
			becomeUser(fout, tblinfo[i].usename);
V
Vadim B. Mikheev 已提交
2451
			dumpSequence(fout, tblinfo[i]);
B
Bruce Momjian 已提交
2452 2453
			if (acls)
				dumpACL(fout, tblinfo[i]);
V
Vadim B. Mikheev 已提交
2454 2455
		}
	}
2456

2457 2458
	for (i = 0; i < numTables; i++)
	{
2459
		if (tblinfo[i].sequence)/* already dumped */
V
Vadim B. Mikheev 已提交
2460
			continue;
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471

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

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

			parentRels = tblinfo[i].parentRels;
			numParents = tblinfo[i].numParents;

2472
			becomeUser(fout, tblinfo[i].usename);
2473

2474
			sprintf(q, "CREATE TABLE \"%s\" (", fmtId(tblinfo[i].relname));
2475 2476 2477 2478 2479 2480 2481 2482 2483
			actual_atts = 0;
			for (j = 0; j < tblinfo[i].numatts; j++)
			{
				if (tblinfo[i].inhAttrs[j] == 0)
				{

					/* Show lengths on bpchar and varchar */
					if (!strcmp(tblinfo[i].typnames[j], "bpchar"))
					{
2484
						sprintf(q, "%s%s\"%s\" char",
2485 2486
								q,
								(actual_atts > 0) ? ", " : "",
2487
								fmtId(tblinfo[i].attnames[j]));
2488

2489 2490
						sprintf(q, "%s(%d)",
								q,
2491
								tblinfo[i].atttypmod[j] - VARHDRSZ);
2492 2493 2494 2495
						actual_atts++;
					}
					else if (!strcmp(tblinfo[i].typnames[j], "varchar"))
					{
2496
						sprintf(q, "%s%s\"%s\" %s",
2497 2498
								q,
								(actual_atts > 0) ? ", " : "",
2499
								fmtId(tblinfo[i].attnames[j]),
2500 2501
								tblinfo[i].typnames[j]);

2502 2503
						sprintf(q, "%s(%d)",
								q,
2504
								tblinfo[i].atttypmod[j] - VARHDRSZ);
2505 2506 2507 2508
						actual_atts++;
					}
					else
					{
2509
						sprintf(q, "%s%s\"%s\" %s",
2510 2511
								q,
								(actual_atts > 0) ? ", " : "",
2512 2513
								fmtId(tblinfo[i].attnames[j]),
								fmtId(tblinfo[i].typnames[j]));
2514 2515
						actual_atts++;
					}
V
Vadim B. Mikheev 已提交
2516 2517
					if (tblinfo[i].adef_expr[j] != NULL)
						sprintf(q, "%s DEFAULT %s", q, tblinfo[i].adef_expr[j]);
2518 2519 2520 2521 2522
					if (tblinfo[i].notnull[j])
						sprintf(q, "%s NOT NULL", q);
				}
			}

2523 2524 2525 2526 2527 2528 2529
			/* put the CONSTRAINTS inside the table def */
			for (k = 0; k < tblinfo[i].ncheck; k++)
			{
				sprintf(q, "%s%s %s",
					q,
					(actual_atts + k > 0) ? ", " : "",
					tblinfo[i].check_expr[k]);
2530 2531
			}

2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546
			strcat(q, ")");

			if (numParents > 0)
			{
				sprintf(q, "%s inherits ( ", q);
				for (k = 0; k < numParents; k++)
				{
					sprintf(q, "%s%s%s",
							q,
							(k > 0) ? ", " : "",
							parentRels[k]);
				}
				strcat(q, ")");
			}

B
Bruce Momjian 已提交
2547 2548
			strcat(q, ";\n");
			fputs(q, fout);
2549
			if (acls)
B
Bruce Momjian 已提交
2550
				dumpACL(fout, tblinfo[i]);
B
Bruce Momjian 已提交
2551

2552 2553
		}
	}
2554 2555 2556 2557
}

/*
 * dumpIndices:
2558
 *	  write out to fout all the user-define indices
2559
 */
2560
void
2561 2562
dumpIndices(FILE *fout, IndInfo *indinfo, int numIndices,
			TableInfo *tblinfo, int numTables, const char *tablename)
2563
{
2564 2565 2566 2567 2568 2569
	int			i,
				k;
	int			tableInd;
	char		attlist[1000];
	char	   *classname[INDEX_MAX_KEYS];
	char	   *funcname;		/* the name of the function to comput the
2570
								 * index key from */
2571 2572 2573
	int			indkey,
				indclass;
	int			nclass;
2574

2575 2576
	char		q[MAXQUERYLEN];
	PGresult   *res;
2577 2578 2579 2580

	for (i = 0; i < numIndices; i++)
	{
		tableInd = findTableByName(tblinfo, numTables,
2581
								   fmtId(indinfo[i].indrelname));
2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639

		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++)
		{
2640
			char	   *attname;
2641 2642 2643 2644 2645 2646 2647 2648 2649 2650

			indkey = atoi(indinfo[i].indkey[k]);
			if (indkey == 0)
				break;
			indkey--;
			if (indkey == ObjectIdAttributeNumber - 1)
				attname = "oid";
			else
				attname = tblinfo[tableInd].attnames[indkey];
			if (funcname)
2651
				sprintf(attlist + strlen(attlist), "%s\"%s\"",
2652
						(k == 0) ? "" : ", ", fmtId(attname));
2653 2654 2655 2656 2657
			else
			{
				if (k >= nclass)
				{
					fprintf(stderr, "dumpIndices(): OpClass not found for "
2658
							"attribute '%s' of index '%s'\n",
2659 2660 2661
							attname, indinfo[i].indexrelname);
					exit_nicely(g_conn);
				}
2662
				sprintf(attlist + strlen(attlist), "%s\"%s\" \"%s\"",
2663
						(k == 0) ? "" : ", ", fmtId(attname), fmtId(classname[k]));
2664 2665 2666 2667 2668 2669 2670
				free(classname[k]);
			}
		}

		if (!tablename || (!strcmp(indinfo[i].indrelname, tablename)))
		{

2671
			sprintf(q, "CREATE %s INDEX \"%s\" on \"%s\" using %s (",
2672
			  (strcmp(indinfo[i].indisunique, "t") == 0) ? "UNIQUE" : "",
2673 2674
					fmtId(indinfo[i].indexrelname),
					fmtId(indinfo[i].indrelname),
2675 2676 2677
					indinfo[i].indamname);
			if (funcname)
			{
2678
				sprintf(q, "%s %s (%s) \"%s\" );\n",
2679
						q, funcname, attlist, fmtId(classname[0]));
2680 2681 2682 2683 2684 2685 2686 2687 2688 2689
				free(funcname);
				free(classname[0]);
			}
			else
				sprintf(q, "%s %s );\n",
						q, attlist);

			fputs(q, fout);
		}
	}
2690 2691

}
2692

2693 2694
/*
 * dumpTuples --
2695 2696 2697 2698 2699
 *	  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
2700
 *	  in PostgreSQL.
2701 2702 2703 2704
 *
 * the attrmap passed in tells how to map the attributes copied in to the
 * attributes copied out
 */
2705
#ifdef NOT_USED
2706
void
2707
dumpTuples(PGresult *res, FILE *fout, int *attrmap)
2708
{
2709 2710 2711 2712 2713
	int			j,
				k;
	int			m,
				n;
	char	  **outVals = NULL; /* values to copy out */
2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732

	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++)
			{
2733
				char	   *pval = outVals[k];
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753

				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);
	}
2754
}
2755

2756
#endif
2757

2758 2759 2760 2761
/*
 * setMaxOid -
 * find the maximum oid and generate a COPY statement to set it
*/
2762

2763
static void
2764
setMaxOid(FILE *fout)
2765
{
2766 2767
	PGresult   *res;
	Oid			max_oid;
2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807

	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)
		fprintf(stderr, "%s maximum system oid is %d %s\n",
				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");
}
2808 2809 2810

/*
 * findLastBuiltInOid -
2811
 * find the last built in oid
2812
 * we do this by looking up the oid of 'template1' in pg_database,
2813
 * this is probably not foolproof but comes close
2814 2815
*/

2816
static int
2817
findLastBuiltinOid(void)
2818
{
2819 2820 2821
	PGresult   *res;
	int			ntups;
	int			last_oid;
2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840

	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;
2841 2842 2843 2844 2845
}


/*
 * checkForQuote:
2846
 *	  checks a string for quote characters and quotes them
2847
 */
2848
static char *
2849
checkForQuote(const char *s)
2850
{
2851 2852 2853
	char	   *r;
	char		c;
	char	   *result;
2854

2855
	int			j = 0;
2856

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

2859 2860
	while ((c = *s) != '\0')
	{
2861

2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872
		if (c == '\'')
		{
			r[j++] = '\'';		/* quote the single quotes */
		}
		r[j++] = c;
		s++;
	}
	r[j] = '\0';

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

2874
	return result;
2875 2876

}
2877 2878


2879
static void
2880
dumpSequence(FILE *fout, TableInfo tbinfo)
2881
{
2882 2883 2884 2885 2886 2887 2888 2889 2890 2891
	PGresult   *res;
	int4		last,
				incby,
				maxv,
				minv,
				cache;
	char		cycled,
				called,
			   *t;
	char		query[MAXQUERYLEN];
2892 2893 2894

	sprintf(query,
			"SELECT sequence_name, last_value, increment_by, max_value, "
2895
			"min_value, cache_value, is_cycled, is_called from \"%s\"",
2896
			fmtId(tbinfo.relname));
2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933

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

	sprintf(query,
2934
			"CREATE SEQUENCE \"%s\" start %d increment %d maxvalue %d "
2935
			"minvalue %d  cache %d %s;\n",
2936
			fmtId(tbinfo.relname), last, incby, maxv, minv, cache,
2937 2938 2939 2940 2941 2942 2943 2944 2945
			(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);
2946 2947

}
V
Vadim B. Mikheev 已提交
2948 2949


2950 2951 2952
static void
dumpTriggers(FILE *fout, const char *tablename,
			 TableInfo *tblinfo, int numTables)
V
Vadim B. Mikheev 已提交
2953
{
2954 2955 2956
	int			i,
				j;

V
Vadim B. Mikheev 已提交
2957 2958 2959
	if (g_verbose)
		fprintf(stderr, "%s dumping out triggers %s\n",
				g_comment_start, g_comment_end);
2960

V
Vadim B. Mikheev 已提交
2961 2962 2963 2964 2965 2966
	for (i = 0; i < numTables; i++)
	{
		if (tablename && strcmp(tblinfo[i].relname, tablename))
			continue;
		for (j = 0; j < tblinfo[i].ntrig; j++)
		{
2967
			becomeUser(fout, tblinfo[i].usename);
V
Vadim B. Mikheev 已提交
2968 2969 2970 2971
			fputs(tblinfo[i].triggers[j], fout);
		}
	}
}
2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993


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

static void becomeUser(FILE *fout, const char *username)
{
	static const char *lastusername = "";

	if (! aclsOption)
		return;

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

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

	lastusername = username;
}