pg_dump.c 86.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.132 2000/01/16 03:54:58 tgl 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 <unistd.h>				/* for getopt() */
55
#include <ctype.h>
56 57

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

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

#include "access/attnum.h"
67
#include "access/htup.h"
68
#include "catalog/pg_index.h"
69
#include "catalog/pg_language.h"
70
#include "catalog/pg_trigger.h"
71
#include "catalog/pg_type.h"
72

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

#include "pg_dump.h"

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

94 95
static void AddAcl(char *aclbuf, const char *keyword);
static char *GetPrivileges(const char *s);
96
static void becomeUser(FILE *fout, const char *username);
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
97

Bruce Momjian's avatar
Bruce Momjian committed
98
extern char *optarg;
99
extern int	optind,
Bruce Momjian's avatar
Bruce Momjian committed
100
			opterr;
101 102

/* global decls */
103
bool		g_verbose;			/* User wants verbose narration of our
Bruce Momjian's avatar
Bruce Momjian committed
104 105 106 107 108 109
								 * activities. */
int			g_last_builtin_oid; /* value of the last builtin oid */
FILE	   *g_fout;				/* the script file */
PGconn	   *g_conn;				/* the database connection */

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

Bruce Momjian's avatar
Bruce Momjian committed
117
char		g_opaque_type[10];	/* name for the opaque type */
118 119

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


static void
125
usage(const char *progname)
126
{
127
	fprintf(stderr,
Bruce Momjian's avatar
Hi,  
Bruce Momjian committed
128 129 130
		"\nUsage: %s [options] dbname\n\n", progname);

#ifdef HAVE_GETOPT_LONG
131
	fprintf(stderr,
132

Bruce Momjian's avatar
Hi,  
Bruce Momjian committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
	"    -a, --data-only         dump out only the data, no schema\n"
	"    -c, --clean             clean(drop) schema prior to create\n"
	"    -d, --insert-proper     dump data as proper insert strings\n"
	"    -D, --insert-attr       dump data as inserts with attribute names\n"
	"    -f, --out file          script output filename\n"
	"    -h, --host hostname     server host name\n"
	"    -n, --no-quotes         suppress most quotes around identifiers\n"
	"    -N, --quotes            enable most quotes around identifiers\n"
	"    -o, --oids              dump object id's (oids)\n"
	"    -p, --port port         server port number\n"
	"    -s, --schema-only       dump out only the schema, no data\n"
	"    -t, --table table       dump for this table only\n"
	"    -u, --password          use password authentication\n"
	"    -v, --verbose           verbose\n"
	"    -x, --no-acl            do not dump ACL's (grant/revoke)\n"
	"    -?, --help              show this help message\n"
149

Bruce Momjian's avatar
Hi,  
Bruce Momjian committed
150 151
	); /* fprintf */
#else
152
	fprintf(stderr,
153

Bruce Momjian's avatar
Hi,  
Bruce Momjian committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
	"    -a                      dump out only the data, no schema\n"
	"    -c                      clean(drop) schema prior to create\n"
	"    -d                      dump data as proper insert strings\n"
	"    -D                      dump data as inserts with attribute names\n"
	"    -f filename             script output filename\n"
	"    -h hostname             server host name\n"
	"    -n                      suppress most quotes around identifiers\n"
	"    -N                      enable most quotes around identifiers\n"
	"    -o                      dump object id's (oids)\n"
	"    -p port                 server port number\n"
	"    -s                      dump out only the schema, no data\n"
	"    -t table                dump for this table only\n"
	"    -u                      use password authentication\n"
	"    -v                      verbose\n"
	"    -x                      do not dump ACL's (grant/revoke)\n"
	"    -?                      show this help message\n"
170

Bruce Momjian's avatar
Hi,  
Bruce Momjian committed
171 172
	); /* fprintf */
#endif
173

174
	fprintf(stderr,
Bruce Momjian's avatar
Hi,  
Bruce Momjian committed
175
		"\nIf dbname is not supplied, then the DATABASE environment variable value is used.\n\n");
176 177

	exit(1);
178 179
}

180
static void
181
exit_nicely(PGconn *conn)
182
{
183 184
	PQfinish(conn);
	exit(1);
185 186 187
}


188 189
/*
 * isViewRule
190
 *				Determine if the relation is a VIEW
191 192
 *
 */
193
static bool
194 195
isViewRule(char *relname)
{
Bruce Momjian's avatar
Bruce Momjian committed
196 197
	PGresult   *res;
	int			ntups;
Bruce Momjian's avatar
Bruce Momjian committed
198
	PQExpBuffer	query = createPQExpBuffer();
199

Bruce Momjian's avatar
Bruce Momjian committed
200 201 202 203
	appendPQExpBuffer(query, "select relname from pg_class, pg_rewrite ");
	appendPQExpBuffer(query, "where pg_class.oid = ev_class ");
	appendPQExpBuffer(query, "and pg_rewrite.ev_type = '1' ");
	appendPQExpBuffer(query, "and rulename = '_RET%s'", relname);
204

Bruce Momjian's avatar
Bruce Momjian committed
205
	res = PQexec(g_conn, query->data);
206 207 208
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
209
		fprintf(stderr, "isViewRule(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
210 211 212 213 214 215 216
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	PQclear(res);
	return ntups > 0 ? TRUE : FALSE;
217
}
218

219 220 221 222
#define COPYBUFSIZ		8192


static void
223
dumpClasses_nodumpData(FILE *fout, const char *classname, const bool oids)
224 225
{

226 227 228 229 230
	PGresult   *res;
	char		query[255];
	int			ret;
	bool		copydone;
	char		copybuf[COPYBUFSIZ];
231

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

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



static void
Bruce Momjian's avatar
Bruce Momjian committed
314
dumpClasses_dumpData(FILE *fout, const char *classname)
315
{
Bruce Momjian's avatar
Bruce Momjian committed
316 317
	PGresult	*res;
	PQExpBuffer	q = createPQExpBuffer();
318 319
	int			tuple;
	int			field;
Bruce Momjian's avatar
Bruce Momjian committed
320
	const char	*expsrc;
321

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

						if (ch == '\\' || ch == '\'')
381
						{
382 383
							putc(ch, fout);			/* double these */
							putc(ch, fout);
384
						}
385 386 387 388 389 390 391 392 393 394 395 396 397
						else if (ch < '\040')
						{
							/* generate octal escape for control chars */
							putc('\\', fout);
							putc(((ch >> 6) & 3) + '0', fout);
							putc(((ch >> 3) & 7) + '0', fout);
							putc((ch & 7) + '0', fout);
						}
						else
							putc(ch, fout);
					}
					putc('\'', fout);
					break;
398
			}
399
		}
400 401 402
		fprintf(fout, ");\n");
	}
	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
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
417
	char	   *all_only;
418 419 420 421

	if (onlytable == NULL)
		all_only = "all";
	else
422
		all_only = "only";
423 424

	if (g_verbose)
425 426 427 428 429
		fprintf(stderr, "%s dumping out the contents of %s %d table%s/sequence%s %s\n",
				g_comment_start, all_only,
				(onlytable == NULL) ? numTables : 1,
				(onlytable == NULL) ? "s" : "", (onlytable == NULL) ? "s" : "",
				g_comment_end);
430

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

	for (i = 0; i < numTables; i++)
	{
451
		const char *classname = tblinfo[i].relname;
452 453 454 455

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

		if (tblinfo[i].sequence)/* already dumped */
458
			continue;
459 460 461 462

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

466 467
			becomeUser(fout, tblinfo[i].usename);

468 469 470
			if (!dumpData)
				dumpClasses_nodumpData(fout, classname, oids);
			else
Bruce Momjian's avatar
Bruce Momjian committed
471
				dumpClasses_dumpData(fout, classname);
472
		}
473
	}
474 475 476
}


477 478 479
static void
prompt_for_password(char *username, char *password)
{
480
	char		buf[512];
Bruce Momjian's avatar
Bruce Momjian committed
481
	int			length;
482 483

#ifdef HAVE_TERMIOS_H
Bruce Momjian's avatar
Bruce Momjian committed
484 485 486
	struct termios t_orig,
				t;

487 488 489
#endif

	printf("Username: ");
490
	fgets(username, 100, stdin);
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
	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
510
	fgets(password, 100, stdin);
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
#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");
}

530

531
int
532
main(int argc, char **argv)
533
{
Bruce Momjian's avatar
Bruce Momjian committed
534 535 536 537 538 539 540
	int			c;
	const char *progname;
	const char *filename = NULL;
	const char *dbname = NULL;
	const char *pghost = NULL;
	const char *pgport = NULL;
	char	   *tablename = NULL;
541
	bool		oids = false;
Bruce Momjian's avatar
Bruce Momjian committed
542 543
	TableInfo  *tblinfo;
	int			numTables;
544 545
	char		connect_string[512] = "";
	char		tmp_string[128];
546 547
	char		username[100];
	char		password[100];
548
	bool		use_password = false;
549

Bruce Momjian's avatar
Hi,  
Bruce Momjian committed
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
#ifdef HAVE_GETOPT_LONG
	static struct option long_options[] = {
		{"data-only", no_argument, NULL, 'a'},
		{"clean", no_argument, NULL, 'c'},
		{"insert-proper",no_argument, NULL, 'd'},
		{"insert-attr",	no_argument, NULL, 'D'},
		{"out", required_argument, NULL, 'f'},
		{"to-file", required_argument, NULL, 'f'},
		{"host", required_argument, NULL, 'h'},
		{"no-quotes", no_argument, NULL, 'n'},
		{"quotes", no_argument, NULL, 'N'},
		{"oids", no_argument, NULL, 'o'},
		{"port", required_argument, NULL, 'p'},
		{"schema-only", no_argument, NULL, 's'},
		{"table", required_argument, NULL, 't'},
		{"password", no_argument, NULL, 'u'},
		{"verbose", no_argument, NULL, 'v'},
		{"no-acl", no_argument, NULL, 'x'},
		{"help", no_argument, NULL, '?'},
569
	};
Bruce Momjian's avatar
Hi,  
Bruce Momjian committed
570 571 572
	int		optindex;
#endif

573
	g_verbose = false;
574
	force_quotes = true;
575
	dropSchema = false;
576 577 578 579 580

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

581
	dataOnly = schemaOnly = dumpData = attrNames = false;
582 583 584

	progname = *argv;

Bruce Momjian's avatar
Hi,  
Bruce Momjian committed
585 586 587 588 589
#ifdef HAVE_GETOPT_LONG
	while ((c = getopt_long(argc, argv, "acdDf:h:nNop:st:uvxz?", long_options, &optindex)) != -1)
#else
	while ((c = getopt(argc, argv, "acdDf:h:nNop:st:uvxz?")) != -1)
#endif
590 591 592
	{
		switch (c)
		{
593
			case 'a':			/* Dump data only */
594
				dataOnly = true;
595
				break;
Bruce Momjian's avatar
Bruce Momjian committed
596 597
			case 'c':			/* clean (i.e., drop) schema prior to
								 * create */
598
				dropSchema = true;
599
				break;
600
			case 'd':			/* dump data as proper insert strings */
601
				dumpData = true;
602 603 604
				break;
			case 'D':			/* dump data as proper insert strings with
								 * attr names */
605 606
				dumpData = true;
				attrNames = true;
607
				break;
608 609 610
			case 'f':			/* output file name */
				filename = optarg;
				break;
611
			case 'h':			/* server host */
612 613
				pghost = optarg;
				break;
Bruce Momjian's avatar
Bruce Momjian committed
614 615
			case 'n':			/* Do not force double-quotes on
								 * identifiers */
616
				force_quotes = false;
617
				break;
618
			case 'N':			/* Force double-quotes on identifiers */
619
				force_quotes = true;
620
				break;
621
			case 'o':			/* Dump oids */
622
				oids = true;
623
				break;
624 625 626
			case 'p':			/* server port */
				pgport = optarg;
				break;
627
			case 's':			/* dump schema only */
628
				schemaOnly = true;
629 630
				break;
			case 't':			/* Dump data for this table only */
631
				{
632
					int			i;
633 634

					tablename = strdup(optarg);
Bruce Momjian's avatar
Bruce Momjian committed
635 636 637 638 639

					/*
					 * quoted string? Then strip quotes and preserve
					 * case...
					 */
640 641 642
					if (tablename[0] == '"')
					{
						strcpy(tablename, &tablename[1]);
Bruce Momjian's avatar
Bruce Momjian committed
643 644
						if (*(tablename + strlen(tablename) - 1) == '"')
							*(tablename + strlen(tablename) - 1) = '\0';
645 646 647 648 649 650 651 652 653
					}
					/* 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]);
					}
654
				}
655
				break;
656 657 658
			case 'u':
				use_password = true;
				break;
659 660
			case 'v':			/* verbose */
				g_verbose = true;
661
				break;
662 663
			case 'x':			/* skip ACL dump */
				aclsSkip = true;
664
				break;
665 666 667 668
			case 'z':			/* Old ACL option bjm 1999/05/27 */
				fprintf(stderr,
				 "%s: The -z option(dump ACLs) is now the default, continuing.\n",
					progname);
669
				break;
670
			case '?':
671 672 673
			default:
				usage(progname);
				break;
674 675 676
		}
	}

677 678 679 680 681 682 683
	if (dumpData == true && oids == true)
	{
		fprintf(stderr,
			 "%s: INSERT's can not set oids, so INSERT and OID options can not be used together.\n",
				progname);
		exit(2);
	}
684

685 686 687 688 689
	/* open the output file */
	if (filename == NULL)
		g_fout = stdout;
	else
	{
690
#ifndef __CYGWIN32__
691
		g_fout = fopen(filename, "w");
692 693 694
#else
		g_fout = fopen(filename, "wb");
#endif
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
		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);
	}

712 713 714 715 716
	/* g_conn = PQsetdb(pghost, pgport, NULL, NULL, dbname); */
	if (pghost != NULL)
	{
		sprintf(tmp_string, "host=%s ", pghost);
		strcat(connect_string, tmp_string);
717
	}
718 719 720 721
	if (pgport != NULL)
	{
		sprintf(tmp_string, "port=%s ", pgport);
		strcat(connect_string, tmp_string);
722
	}
723 724 725 726
	if (dbname != NULL)
	{
		sprintf(tmp_string, "dbname=%s ", dbname);
		strcat(connect_string, tmp_string);
727
	}
728 729 730 731 732 733 734 735
	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);
736 737
		MemSet(tmp_string, 0, sizeof(tmp_string));
		MemSet(password, 0, sizeof(password));
738 739
	}
	g_conn = PQconnectdb(connect_string);
740
	MemSet(connect_string, 0, sizeof(connect_string));
741 742 743 744 745 746 747 748
	/* 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);
	}

749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
	/*
	 * Start serializable transaction to dump consistent data
	 */
	{
		PGresult   *res;

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

771 772
	g_last_builtin_oid = findLastBuiltinOid();

773
	if (oids == true)
774 775 776 777
		setMaxOid(g_fout);
	if (!dataOnly)
	{
		if (g_verbose)
778
			fprintf(stderr, "%s last builtin oid is %u %s\n",
779
					g_comment_start, g_last_builtin_oid, g_comment_end);
780
		tblinfo = dumpSchema(g_fout, &numTables, tablename, aclsSkip);
781 782
	}
	else
783
		tblinfo = dumpSchema(NULL, &numTables, tablename, aclsSkip);
784 785 786 787

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

788 789
	if (!dataOnly)				/* dump indexes and triggers at the end
								 * for performance */
790 791 792
	{
		dumpSchemaIdx(g_fout, tablename, tblinfo, numTables);
		dumpTriggers(g_fout, tablename, tblinfo, numTables);
793
		dumpRules(g_fout, tablename, tblinfo, numTables);
794
	}
795 796

	fflush(g_fout);
797 798 799
	if (g_fout != stdout)
		fclose(g_fout);

800 801 802
	clearTableInfo(tblinfo, numTables);
	PQfinish(g_conn);
	exit(0);
803 804 805
}

/*
806 807
 * getTypes:
 *	  read all base types in the system catalogs and return them in the
808 809
 * TypeInfo* structure
 *
810
 *	numTypes is set to the number of types read in
811 812
 *
 */
813
TypeInfo   *
814 815
getTypes(int *numTypes)
{
Bruce Momjian's avatar
Bruce Momjian committed
816
	PGresult   *res;
817 818
	int			ntups;
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
819
	PQExpBuffer	query = createPQExpBuffer();
Bruce Momjian's avatar
Bruce Momjian committed
820
	TypeInfo   *tinfo;
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836

	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;
837 838 839 840 841 842 843 844 845 846 847 848

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

Bruce Momjian's avatar
Bruce Momjian committed
849
	appendPQExpBuffer(query, "SELECT pg_type.oid, typowner, typname, typlen, typprtlen, "
850
		  "typinput, typoutput, typreceive, typsend, typelem, typdelim, "
Bruce Momjian's avatar
Bruce Momjian committed
851
		  "typdefault, typrelid, typbyval, usename from pg_type, pg_user "
852 853
			"where typowner = usesysid");

Bruce Momjian's avatar
Bruce Momjian committed
854
	res = PQexec(g_conn, query->data);
855 856 857
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
858
		fprintf(stderr, "getTypes(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
859 860 861 862 863 864 865 866 867 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
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

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

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

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

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

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

	*numTypes = ntups;

	PQclear(res);

	return tinfo;
919 920 921 922
}

/*
 * getOperators:
923
 *	  read all operators in the system catalogs and return them in the
924 925
 * OprInfo* structure
 *
926 927
 *	numOprs is set to the number of operators read in
 *
928 929
 *
 */
930
OprInfo    *
931 932
getOperators(int *numOprs)
{
Bruce Momjian's avatar
Bruce Momjian committed
933
	PGresult	*res;
934 935
	int			ntups;
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
936
	PQExpBuffer	query = createPQExpBuffer();
937

Bruce Momjian's avatar
Bruce Momjian committed
938
	OprInfo    *oprinfo;
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953

	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;
954 955 956 957 958 959

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

Bruce Momjian's avatar
Bruce Momjian committed
960
	appendPQExpBuffer(query, "SELECT pg_operator.oid, oprname, oprkind, oprcode, "
961 962 963 964 965
			"oprleft, oprright, oprcom, oprnegate, oprrest, oprjoin, "
			"oprcanhash, oprlsortop, oprrsortop, usename "
			"from pg_operator, pg_user "
			"where oprowner = usesysid");

Bruce Momjian's avatar
Bruce Momjian committed
966
	res = PQexec(g_conn, query->data);
967 968 969
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
970
		fprintf(stderr, "getOperators(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
		exit_nicely(g_conn);
	}

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

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

	i_oid = PQfnumber(res, "oid");
	i_oprname = PQfnumber(res, "oprname");
	i_oprkind = PQfnumber(res, "oprkind");
	i_oprcode = PQfnumber(res, "oprcode");
	i_oprleft = PQfnumber(res, "oprleft");
	i_oprright = PQfnumber(res, "oprright");
	i_oprcom = PQfnumber(res, "oprcom");
	i_oprnegate = PQfnumber(res, "oprnegate");
	i_oprrest = PQfnumber(res, "oprrest");
	i_oprjoin = PQfnumber(res, "oprjoin");
	i_oprcanhash = PQfnumber(res, "oprcanhash");
	i_oprlsortop = PQfnumber(res, "oprlsortop");
	i_oprrsortop = PQfnumber(res, "oprrsortop");
	i_usename = PQfnumber(res, "usename");

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

	PQclear(res);

	return oprinfo;
1015 1016
}

1017
void
1018
clearTypeInfo(TypeInfo *tp, int numTypes)
1019
{
1020
	int			i;
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053

	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);
1054 1055 1056
}

void
1057
clearFuncInfo(FuncInfo *fun, int numFuncs)
1058
{
1059 1060
	int			i,
				a;
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071

	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);
1072
		for (a = 0; a < FUNC_MAX_ARGS ; ++a)
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
			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);
1083 1084
}

1085
static void
1086
clearTableInfo(TableInfo *tblinfo, int numTables)
1087
{
1088 1089
	int			i,
				j;
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114

	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]);
		}
1115 1116
		if (tblinfo[i].atttypmod)
			free((int *) tblinfo[i].atttypmod);
1117 1118 1119 1120 1121 1122 1123 1124
		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);
1125 1126
	if (tblinfo[i].primary_key)
	    free(tblinfo[i].primary_key);
1127 1128
	}
	free(tblinfo);
1129 1130
}

1131
void
1132
clearInhInfo(InhInfo *inh, int numInherits)
1133
{
1134
	int			i;
1135 1136 1137 1138 1139

	if (!inh)
		return;
	for (i = 0; i < numInherits; ++i)
	{
1140 1141
		if (inh[i].inhrelid)
			free(inh[i].inhrelid);
1142 1143 1144 1145
		if (inh[i].inhparent)
			free(inh[i].inhparent);
	}
	free(inh);
1146 1147 1148
}

void
1149
clearOprInfo(OprInfo *opr, int numOprs)
1150
{
1151
	int			i;
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186

	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);
1187 1188 1189
}

void
1190
clearIndInfo(IndInfo *ind, int numIndices)
1191
{
1192 1193
	int			i,
				a;
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217

	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);
1218 1219 1220
}

void
Bruce Momjian's avatar
Bruce Momjian committed
1221
clearAggInfo(AggInfo *agginfo, int numArgs)
1222
{
1223
	int			i;
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

	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);
1253
}
1254 1255 1256

/*
 * getAggregates:
1257
 *	  read all the user-defined aggregates in the system catalogs and
1258 1259
 * return them in the AggInfo* structure
 *
1260 1261
 * numAggs is set to the number of aggregates read in
 *
1262 1263
 *
 */
1264
AggInfo    *
1265 1266
getAggregates(int *numAggs)
{
Bruce Momjian's avatar
Bruce Momjian committed
1267
	PGresult   *res;
1268 1269
	int			ntups;
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
1270
	PQExpBuffer	query = createPQExpBuffer();
Bruce Momjian's avatar
Bruce Momjian committed
1271
	AggInfo    *agginfo;
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283

	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;
1284 1285 1286

	/* find all user-defined aggregates */

Bruce Momjian's avatar
Bruce Momjian committed
1287
	appendPQExpBuffer(query,
1288 1289 1290 1291 1292
			"SELECT pg_aggregate.oid, aggname, aggtransfn1, aggtransfn2, "
			"aggfinalfn, aggtranstype1, aggbasetype, aggtranstype2, "
		  "agginitval1, agginitval2, usename from pg_aggregate, pg_user "
			"where aggowner = usesysid");

Bruce Momjian's avatar
Bruce Momjian committed
1293
	res = PQexec(g_conn, query->data);
1294 1295 1296
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1297
		fprintf(stderr, "getAggregates(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1298 1299 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
		exit_nicely(g_conn);
	}

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

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

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

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

	PQclear(res);

	return agginfo;
1336 1337 1338 1339
}

/*
 * getFuncs:
1340
 *	  read all the user-defined functions in the system catalogs and
1341 1342
 * return them in the FuncInfo* structure
 *
1343 1344
 * numFuncs is set to the number of functions read in
 *
1345 1346
 *
 */
1347
FuncInfo   *
1348 1349
getFuncs(int *numFuncs)
{
Bruce Momjian's avatar
Bruce Momjian committed
1350
	PGresult	*res;
1351 1352
	int			ntups;
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
1353 1354
	PQExpBuffer	query = createPQExpBuffer();
	FuncInfo	*finfo;
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365

	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;
1366 1367 1368

	/* find all user-defined funcs */

Bruce Momjian's avatar
Bruce Momjian committed
1369
	appendPQExpBuffer(query,
1370 1371 1372
			"SELECT pg_proc.oid, proname, prolang, pronargs, prorettype, "
			"proretset, proargtypes, prosrc, probin, usename "
			"from pg_proc, pg_user "
1373
			"where pg_proc.oid > '%u'::oid and proowner = usesysid",
1374 1375
			g_last_builtin_oid);

Bruce Momjian's avatar
Bruce Momjian committed
1376
	res = PQexec(g_conn, query->data);
1377 1378 1379
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1380
		fprintf(stderr, "getFuncs(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1381 1382 1383 1384 1385 1386 1387 1388 1389
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numFuncs = ntups;

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

1390 1391
	memset((char *) finfo, 0, ntups * sizeof(FuncInfo));

1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
	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));
1414
		finfo[i].lang = atoi(PQgetvalue(res, i, i_prolang));
1415
		finfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1416 1417 1418 1419 1420 1421 1422 1423 1424
		if (finfo[i].nargs < 0 || finfo[i].nargs > FUNC_MAX_ARGS)
		{
			fprintf(stderr, "failed sanity check: %s has %d args\n",
					finfo[i].proname, finfo[i].nargs);
			exit(2);
		}
		parseNumericArray(PQgetvalue(res, i, i_proargtypes),
						  finfo[i].argtypes,
						  finfo[i].nargs);
1425 1426 1427 1428 1429 1430
		finfo[i].dumped = 0;
	}

	PQclear(res);

	return finfo;
1431 1432 1433 1434 1435

}

/*
 * getTables
1436
 *	  read all the user-defined tables (no indices, no catalogs)
1437 1438
 * in the system catalogs return them in the TableInfo* structure
 *
1439 1440
 * numTables is set to the number of tables read in
 *
1441 1442
 *
 */
1443
TableInfo  *
1444
getTables(int *numTables, FuncInfo *finfo, int numFuncs)
1445
{
Bruce Momjian's avatar
Bruce Momjian committed
1446
	PGresult	*res;
1447 1448
	int			ntups;
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
1449 1450
	PQExpBuffer	query = createPQExpBuffer();
	TableInfo	*tblinfo;
1451 1452 1453 1454 1455 1456

	int			i_oid;
	int			i_relname;
	int			i_relkind;
	int			i_relacl;
	int			i_usename;
1457 1458
	int			i_relchecks;
	int			i_reltriggers;
Bruce Momjian's avatar
Bruce Momjian committed
1459
    int         i_relhasindex;
1460 1461 1462 1463 1464 1465

	/*
	 * 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*
	 *
1466 1467 1468
	 * we ignore tables that are not type 'r' (ordinary relation)
	 * or 'S' (sequence) --- in particular, Large Object relations
	 * (type 'l') are ignored.
1469 1470
	 */

Bruce Momjian's avatar
Bruce Momjian committed
1471
	appendPQExpBuffer(query,
1472
			"SELECT pg_class.oid, relname, relkind, relacl, usename, "
Bruce Momjian's avatar
Bruce Momjian committed
1473
			"relchecks, reltriggers, relhasindex "
1474 1475 1476
			"from pg_class, pg_user "
			"where relowner = usesysid and "
			"(relkind = 'r' or relkind = 'S') and relname !~ '^pg_' "
1477
			"order by oid");
1478

Bruce Momjian's avatar
Bruce Momjian committed
1479
	res = PQexec(g_conn, query->data);
1480 1481 1482
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1483
		fprintf(stderr, "getTables(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
		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");
1498 1499
	i_relchecks = PQfnumber(res, "relchecks");
	i_reltriggers = PQfnumber(res, "reltriggers");
Bruce Momjian's avatar
Bruce Momjian committed
1500
	i_relhasindex = PQfnumber(res, "relhasindex");
1501 1502 1503 1504 1505 1506 1507 1508

	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));
1509 1510
		tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
		tblinfo[i].ntrig = atoi(PQgetvalue(res, i, i_reltriggers));
1511

Bruce Momjian's avatar
Bruce Momjian committed
1512 1513 1514
		/*
		 * Exclude inherited CHECKs from CHECK constraints total. If a
		 * constraint matches by name and condition with a constraint
1515 1516 1517 1518
		 * belonging to a parent class, we assume it was inherited.
		 */
		if (tblinfo[i].ncheck > 0)
		{
Bruce Momjian's avatar
Bruce Momjian committed
1519
			PGresult   *res2;
1520 1521
			int			ntups2;

Bruce Momjian's avatar
Bruce Momjian committed
1522
			if (g_verbose)
1523 1524 1525 1526 1527 1528
				fprintf(stderr, "%s excluding inherited CHECK constraints "
						"for relation: '%s' %s\n",
						g_comment_start,
						tblinfo[i].relname,
						g_comment_end);

Bruce Momjian's avatar
Bruce Momjian committed
1529 1530
			resetPQExpBuffer(query);
			appendPQExpBuffer(query, "SELECT rcname from pg_relcheck, pg_inherits as i "
1531
					"where rcrelid = '%s'::oid "
1532
					" and rcrelid = i.inhrelid"
1533 1534 1535 1536 1537 1538
					" 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);
Bruce Momjian's avatar
Bruce Momjian committed
1539
			res2 = PQexec(g_conn, query->data);
1540 1541 1542
			if (!res2 ||
				PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
1543
				fprintf(stderr, "getTables(): SELECT (for inherited CHECK) failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
				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 */
1559 1560 1561
		if (tblinfo[i].ncheck > 0)
		{
			PGresult   *res2;
1562 1563
			int			i_rcname,
						i_rcsrc;
1564 1565
			int			ntups2;
			int			i2;
1566

1567
			if (g_verbose)
1568
				fprintf(stderr, "%s finding CHECK constraints for relation: '%s' %s\n",
1569 1570 1571
						g_comment_start,
						tblinfo[i].relname,
						g_comment_end);
1572

Bruce Momjian's avatar
Bruce Momjian committed
1573 1574
			resetPQExpBuffer(query);
			appendPQExpBuffer(query, "SELECT rcname, rcsrc from pg_relcheck "
1575 1576 1577
					"where rcrelid = '%s'::oid "
					"   and not exists "
					"  (select * from pg_relcheck as c, pg_inherits as i "
1578
					"   where i.inhrelid = pg_relcheck.rcrelid "
1579 1580 1581
					"     and c.rcname = pg_relcheck.rcname "
					"     and c.rcsrc = pg_relcheck.rcsrc "
					"     and c.rcrelid = i.inhparent) ",
1582
					tblinfo[i].oid);
Bruce Momjian's avatar
Bruce Momjian committed
1583
			res2 = PQexec(g_conn, query->data);
1584
			if (!res2 ||
1585
				PQresultStatus(res2) != PGRES_TUPLES_OK)
1586
			{
1587
				fprintf(stderr, "getTables(): SELECT (for CHECK) failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1588 1589 1590 1591 1592
				exit_nicely(g_conn);
			}
			ntups2 = PQntuples(res2);
			if (ntups2 != tblinfo[i].ncheck)
			{
1593
				fprintf(stderr, "getTables(): relation '%s': %d CHECKs were expected, but got %d\n",
1594
						tblinfo[i].relname, tblinfo[i].ncheck, ntups2);
1595 1596 1597 1598
				exit_nicely(g_conn);
			}
			i_rcname = PQfnumber(res2, "rcname");
			i_rcsrc = PQfnumber(res2, "rcsrc");
1599
			tblinfo[i].check_expr = (char **) malloc(ntups2 * sizeof(char *));
1600 1601
			for (i2 = 0; i2 < ntups2; i2++)
			{
Bruce Momjian's avatar
Bruce Momjian committed
1602 1603
				const char *name = PQgetvalue(res2, i2, i_rcname);
				const char *expr = PQgetvalue(res2, i2, i_rcsrc);
1604

Bruce Momjian's avatar
Bruce Momjian committed
1605
				resetPQExpBuffer(query);
Bruce Momjian's avatar
Bruce Momjian committed
1606 1607 1608 1609 1610 1611 1612 1613
				if (name[0] != '$') {
					appendPQExpBuffer(query, "CONSTRAINT ");
					appendPQExpBuffer(query, fmtId(name, force_quotes));
					appendPQExpBufferChar(query, ' ');
				}
				appendPQExpBuffer(query, "CHECK (");
				appendPQExpBuffer(query, expr);
				appendPQExpBuffer(query, ")");
Bruce Momjian's avatar
Bruce Momjian committed
1614
				tblinfo[i].check_expr[i2] = strdup(query->data);
1615 1616 1617 1618 1619
			}
			PQclear(res2);
		}
		else
			tblinfo[i].check_expr = NULL;
1620

1621 1622 1623 1624 1625 1626
	/* Get primary key */
	if (strcmp(PQgetvalue(res, i, i_relhasindex), "t")==0)
	{
	    PGresult * res2;
	    char str[INDEX_MAX_KEYS * NAMEDATALEN + 3] = "";
	    int j;
Bruce Momjian's avatar
Bruce Momjian committed
1627

Bruce Momjian's avatar
Bruce Momjian committed
1628
			resetPQExpBuffer(query);
Bruce Momjian's avatar
Bruce Momjian committed
1629
			appendPQExpBuffer(query,
1630 1631 1632 1633 1634 1635 1636
		    "SELECT a.attname "
		    "FROM pg_index i, pg_class c, pg_attribute a "
		    "WHERE i.indisprimary AND i.indrelid = %s "
		    "  AND i.indexrelid = c.oid AND a.attnum > 0 AND a.attrelid = c.oid "
		    "ORDER BY a.attnum ",
		    tblinfo[i].oid);
	    res2 = PQexec(g_conn, query->data);
Bruce Momjian's avatar
Bruce Momjian committed
1637 1638 1639
			if (!res2 || PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
				fprintf(stderr, "getTables(): SELECT (for PRIMARY KEY) failed.  Explanation from backend: %s",
1640
			PQerrorMessage(g_conn));
Bruce Momjian's avatar
Bruce Momjian committed
1641 1642
				exit_nicely(g_conn);
			}
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662

	    for (j = 0; j < PQntuples(res2); j++)
	    {
		if (strlen(str)>0)
		    strcat(str, ", ");
		strcat(str, fmtId(PQgetvalue(res2, j, 0), force_quotes));
	    }

	    if (strlen(str)>0) {
		tblinfo[i].primary_key = strdup(str);
		if (tblinfo[i].primary_key == NULL) {
		    perror("strdup");
		    exit(1);
		}
	    }
	    else
		tblinfo[i].primary_key = NULL;
	}
	else
	    tblinfo[i].primary_key = NULL;
Bruce Momjian's avatar
Bruce Momjian committed
1663

1664 1665 1666 1667
		/* Get Triggers */
		if (tblinfo[i].ntrig > 0)
		{
			PGresult   *res2;
1668 1669 1670 1671 1672
			int			i_tgname,
						i_tgfoid,
						i_tgtype,
						i_tgnargs,
						i_tgargs;
1673 1674
			int			ntups2;
			int			i2;
1675

1676
			if (g_verbose)
1677
				fprintf(stderr, "%s finding Triggers for relation: '%s' %s\n",
1678 1679 1680
						g_comment_start,
						tblinfo[i].relname,
						g_comment_end);
1681

Bruce Momjian's avatar
Bruce Momjian committed
1682 1683
			resetPQExpBuffer(query);
			appendPQExpBuffer(query, "SELECT tgname, tgfoid, tgtype, tgnargs, tgargs "
1684 1685 1686
					"from pg_trigger "
					"where tgrelid = '%s'::oid ",
					tblinfo[i].oid);
Bruce Momjian's avatar
Bruce Momjian committed
1687
			res2 = PQexec(g_conn, query->data);
1688
			if (!res2 ||
1689
				PQresultStatus(res2) != PGRES_TUPLES_OK)
1690
			{
1691
				fprintf(stderr, "getTables(): SELECT (for TRIGGER) failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1692 1693 1694 1695 1696
				exit_nicely(g_conn);
			}
			ntups2 = PQntuples(res2);
			if (ntups2 != tblinfo[i].ntrig)
			{
1697
				fprintf(stderr, "getTables(): relation '%s': %d Triggers were expected, but got %d\n",
1698
						tblinfo[i].relname, tblinfo[i].ntrig, ntups2);
1699 1700 1701 1702 1703 1704 1705
				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");
1706
			tblinfo[i].triggers = (char **) malloc(ntups2 * sizeof(char *));
Bruce Momjian's avatar
Bruce Momjian committed
1707 1708
			resetPQExpBuffer(query);
			for (i2 = 0; i2 < ntups2; i2++)
1709
			{
Bruce Momjian's avatar
Bruce Momjian committed
1710
				const char *tgfunc = PQgetvalue(res2, i2, i_tgfoid);
1711 1712
				int2		tgtype = atoi(PQgetvalue(res2, i2, i_tgtype));
				int			tgnargs = atoi(PQgetvalue(res2, i2, i_tgnargs));
Bruce Momjian's avatar
Bruce Momjian committed
1713 1714
				const char *tgargs = PQgetvalue(res2, i2, i_tgargs);
				const char *p;
Bruce Momjian's avatar
Bruce Momjian committed
1715
				PQExpBuffer	farg = createPQExpBuffer();
1716 1717
				int			findx;

1718 1719 1720
				for (findx = 0; findx < numFuncs; findx++)
				{
					if (strcmp(finfo[findx].oid, tgfunc) == 0 &&
1721
						finfo[findx].nargs == 0 &&
1722 1723 1724 1725 1726
						strcmp(finfo[findx].prorettype, "0") == 0)
						break;
				}
				if (findx == numFuncs)
				{
1727
					fprintf(stderr, "getTables(): relation '%s': cannot find function with oid %s for trigger %s\n",
1728
							tblinfo[i].relname, tgfunc, PQgetvalue(res2, i2, i_tgname));
1729 1730 1731
					exit_nicely(g_conn);
				}
				tgfunc = finfo[findx].proname;
1732

Bruce Momjian's avatar
Bruce Momjian committed
1733
#if 0
1734
				/* XXX - how to emit this DROP TRIGGER? */
1735
				if (dropSchema)
Bruce Momjian's avatar
Bruce Momjian committed
1736
				{
Bruce Momjian's avatar
Bruce Momjian committed
1737 1738
					resetPQExpBuffer(query);
					appendPQExpBuffer(query, "DROP TRIGGER %s ON %s;\n",
Bruce Momjian's avatar
Bruce Momjian committed
1739 1740
					 fmtId(PQgetvalue(res2, i2, i_tgname), force_quotes),
							fmtId(tblinfo[i].relname, force_quotes));
Bruce Momjian's avatar
Bruce Momjian committed
1741
					fputs(query->data, fout);
Bruce Momjian's avatar
Bruce Momjian committed
1742
				}
1743 1744
#endif

Bruce Momjian's avatar
Bruce Momjian committed
1745
				resetPQExpBuffer(query);
Bruce Momjian's avatar
Bruce Momjian committed
1746 1747 1748
				appendPQExpBuffer(query, "CREATE TRIGGER ");
				appendPQExpBuffer(query, fmtId(PQgetvalue(res2, i2, i_tgname), force_quotes));
				appendPQExpBufferChar(query, ' ');
1749 1750 1751
				/* Trigger type */
				findx = 0;
				if (TRIGGER_FOR_BEFORE(tgtype))
Bruce Momjian's avatar
Bruce Momjian committed
1752
					appendPQExpBuffer(query, "BEFORE");
1753
				else
Bruce Momjian's avatar
Bruce Momjian committed
1754
					appendPQExpBuffer(query, "AFTER");
1755 1756
				if (TRIGGER_FOR_INSERT(tgtype))
				{
Bruce Momjian's avatar
Bruce Momjian committed
1757
					appendPQExpBuffer(query, " INSERT");
1758 1759 1760 1761 1762
					findx++;
				}
				if (TRIGGER_FOR_DELETE(tgtype))
				{
					if (findx > 0)
Bruce Momjian's avatar
Bruce Momjian committed
1763
						appendPQExpBuffer(query, " OR DELETE");
1764
					else
Bruce Momjian's avatar
Bruce Momjian committed
1765
						appendPQExpBuffer(query, " DELETE");
1766 1767 1768
					findx++;
				}
				if (TRIGGER_FOR_UPDATE(tgtype))
1769
				{
1770
					if (findx > 0)
Bruce Momjian's avatar
Bruce Momjian committed
1771
						appendPQExpBuffer(query, " OR UPDATE");
1772
					else
Bruce Momjian's avatar
Bruce Momjian committed
1773
						appendPQExpBuffer(query, " UPDATE");
1774
				}
Bruce Momjian's avatar
Bruce Momjian committed
1775 1776
				appendPQExpBuffer(query, " ON %s FOR EACH ROW EXECUTE PROCEDURE %s (",
					fmtId(tblinfo[i].relname, force_quotes), tgfunc);
1777 1778
				for (findx = 0; findx < tgnargs; findx++)
				{
Bruce Momjian's avatar
Bruce Momjian committed
1779
					const char	   *s;
1780 1781

					for (p = tgargs;;)
1782
					{
1783
						p = strchr(p, '\\');
1784 1785
						if (p == NULL)
						{
1786
							fprintf(stderr, "getTables(): relation '%s': bad argument string (%s) for trigger '%s'\n",
1787 1788 1789
									tblinfo[i].relname,
									PQgetvalue(res2, i2, i_tgargs),
									PQgetvalue(res2, i2, i_tgname));
1790 1791 1792 1793 1794 1795 1796 1797
							exit_nicely(g_conn);
						}
						p++;
						if (*p == '\\')
						{
							p++;
							continue;
						}
1798
						if (p[0] == '0' && p[1] == '0' && p[2] == '0')
1799 1800 1801
							break;
					}
					p--;
Bruce Momjian's avatar
Bruce Momjian committed
1802
					for (s = tgargs; s < p;)
1803 1804
					{
						if (*s == '\'')
Bruce Momjian's avatar
Bruce Momjian committed
1805 1806
							appendPQExpBufferChar(farg, '\\');
						appendPQExpBufferChar(farg, *s++);
1807
					}
Bruce Momjian's avatar
Bruce Momjian committed
1808 1809 1810 1811
					appendPQExpBufferChar(query, '\'');
					appendPQExpBuffer(query, farg->data);
					appendPQExpBufferChar(query, '\'');
					appendPQExpBuffer(query, (findx < tgnargs - 1) ? ", " : "");
1812 1813
					tgargs = p + 4;
				}
Bruce Momjian's avatar
Bruce Momjian committed
1814 1815
				appendPQExpBuffer(query, ");\n");
				tblinfo[i].triggers[i2] = strdup(query->data);
1816 1817 1818 1819 1820
			}
			PQclear(res2);
		}
		else
			tblinfo[i].triggers = NULL;
1821 1822 1823 1824 1825
	}

	PQclear(res);

	return tblinfo;
1826 1827 1828 1829 1830

}

/*
 * getInherits
1831
 *	  read all the inheritance information
1832 1833
 * from the system catalogs return them in the InhInfo* structure
 *
1834 1835
 * numInherits is set to the number of tables read in
 *
1836 1837
 *
 */
1838
InhInfo    *
1839 1840
getInherits(int *numInherits)
{
Bruce Momjian's avatar
Bruce Momjian committed
1841
	PGresult	*res;
1842 1843
	int			ntups;
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
1844 1845
	PQExpBuffer	query = createPQExpBuffer();
	InhInfo		*inhinfo;
1846

1847
	int			i_inhrelid;
1848
	int			i_inhparent;
1849 1850 1851

	/* find all the inheritance information */

Bruce Momjian's avatar
Bruce Momjian committed
1852
	appendPQExpBuffer(query, "SELECT inhrelid, inhparent from pg_inherits");
1853

Bruce Momjian's avatar
Bruce Momjian committed
1854
	res = PQexec(g_conn, query->data);
1855 1856 1857
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1858
		fprintf(stderr, "getInherits(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1859 1860 1861 1862 1863 1864 1865 1866 1867
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numInherits = ntups;

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

1868
	i_inhrelid = PQfnumber(res, "inhrelid");
1869 1870 1871 1872
	i_inhparent = PQfnumber(res, "inhparent");

	for (i = 0; i < ntups; i++)
	{
1873
		inhinfo[i].inhrelid = strdup(PQgetvalue(res, i, i_inhrelid));
1874 1875 1876 1877 1878
		inhinfo[i].inhparent = strdup(PQgetvalue(res, i, i_inhparent));
	}

	PQclear(res);
	return inhinfo;
1879 1880 1881 1882
}

/*
 * getTableAttrs -
1883 1884
 *	  for each table in tblinfo, read its attributes types and names
 *
1885
 * this is implemented in a very inefficient way right now, looping
1886
 * through the tblinfo and doing a join per table to find the attrs and their
1887 1888
 * types
 *
1889
 *	modifies tblinfo
1890 1891
 */
void
1892
getTableAttrs(TableInfo *tblinfo, int numTables)
1893
{
1894 1895
	int			i,
				j;
Bruce Momjian's avatar
Bruce Momjian committed
1896
	PQExpBuffer	q = createPQExpBuffer();
1897 1898
	int			i_attname;
	int			i_typname;
1899
	int			i_atttypmod;
1900
	int			i_attnotnull;
1901
	int			i_atthasdef;
Bruce Momjian's avatar
Bruce Momjian committed
1902
	PGresult	*res;
1903
	int			ntups;
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918

	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)
1919
			fprintf(stderr, "%s finding the attrs and types for table: '%s' %s\n",
1920 1921 1922 1923
					g_comment_start,
					tblinfo[i].relname,
					g_comment_end);

Bruce Momjian's avatar
Bruce Momjian committed
1924 1925
		resetPQExpBuffer(q);
		appendPQExpBuffer(q, "SELECT a.attnum, a.attname, t.typname, a.atttypmod, "
1926
				"a.attnotnull, a.atthasdef "
1927 1928 1929 1930
				"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);
Bruce Momjian's avatar
Bruce Momjian committed
1931
		res = PQexec(g_conn, q->data);
1932 1933 1934
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
1935
			fprintf(stderr, "getTableAttrs(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1936 1937 1938 1939 1940 1941 1942
			exit_nicely(g_conn);
		}

		ntups = PQntuples(res);

		i_attname = PQfnumber(res, "attname");
		i_typname = PQfnumber(res, "typname");
1943
		i_atttypmod = PQfnumber(res, "atttypmod");
1944
		i_attnotnull = PQfnumber(res, "attnotnull");
1945
		i_atthasdef = PQfnumber(res, "atthasdef");
1946 1947 1948 1949

		tblinfo[i].numatts = ntups;
		tblinfo[i].attnames = (char **) malloc(ntups * sizeof(char *));
		tblinfo[i].typnames = (char **) malloc(ntups * sizeof(char *));
1950
		tblinfo[i].atttypmod = (int *) malloc(ntups * sizeof(int));
1951 1952
		tblinfo[i].inhAttrs = (int *) malloc(ntups * sizeof(int));
		tblinfo[i].notnull = (bool *) malloc(ntups * sizeof(bool));
1953
		tblinfo[i].adef_expr = (char **) malloc(ntups * sizeof(char *));
1954 1955 1956 1957 1958 1959
		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));
1960
			tblinfo[i].atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
1961 1962 1963
			tblinfo[i].inhAttrs[j] = 0; /* this flag is set in
										 * flagInhAttrs() */
			tblinfo[i].notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't') ? true : false;
1964 1965 1966
			if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
			{
				PGresult   *res2;
1967

1968
				if (g_verbose)
1969
					fprintf(stderr, "%s finding DEFAULT expression for attr: '%s' %s\n",
1970 1971 1972
							g_comment_start,
							tblinfo[i].attnames[j],
							g_comment_end);
1973

Bruce Momjian's avatar
Bruce Momjian committed
1974 1975
				resetPQExpBuffer(q);
				appendPQExpBuffer(q, "SELECT adsrc from pg_attrdef "
1976 1977
						"where adrelid = '%s'::oid and adnum = %d ",
						tblinfo[i].oid, j + 1);
Bruce Momjian's avatar
Bruce Momjian committed
1978
				res2 = PQexec(g_conn, q->data);
1979
				if (!res2 ||
1980
					PQresultStatus(res2) != PGRES_TUPLES_OK)
1981
				{
1982
					fprintf(stderr, "getTableAttrs(): SELECT (for DEFAULT) failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1983 1984 1985 1986 1987 1988 1989
					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;
1990 1991 1992
		}
		PQclear(res);
	}
1993 1994 1995 1996 1997
}


/*
 * getIndices
1998
 *	  read all the user-defined indices information
1999 2000
 * from the system catalogs return them in the InhInfo* structure
 *
2001 2002
 * numIndices is set to the number of indices read in
 *
2003 2004
 *
 */
2005
IndInfo    *
2006 2007
getIndices(int *numIndices)
{
2008
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
2009
	PQExpBuffer	query = createPQExpBuffer();
Bruce Momjian's avatar
Bruce Momjian committed
2010
	PGresult   *res;
2011
	int			ntups;
Bruce Momjian's avatar
Bruce Momjian committed
2012
	IndInfo    *indinfo;
2013 2014 2015 2016 2017 2018 2019 2020

	int			i_indexrelname;
	int			i_indrelname;
	int			i_indamname;
	int			i_indproc;
	int			i_indkey;
	int			i_indclass;
	int			i_indisunique;
2021 2022 2023 2024 2025

	/*
	 * find all the user-defined indices. We do not handle partial
	 * indices.
	 *
2026
	 * Notice we skip indices on inversion objects (relkind 'l')
2027 2028 2029 2030
	 *
	 * this is a 4-way join !!
	 */

Bruce Momjian's avatar
Bruce Momjian committed
2031
	appendPQExpBuffer(query,
2032
	    "SELECT t1.relname as indexrelname, t2.relname as indrelname, "
2033 2034 2035
			"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 "
Bruce Momjian's avatar
Bruce Momjian committed
2036
			"WHERE t1.oid = i.indexrelid and t2.oid = i.indrelid "
2037
			"and t1.relam = a.oid and i.indexrelid > '%u'::oid "
Bruce Momjian's avatar
Bruce Momjian committed
2038
			"and t2.relname !~ '^pg_' and t2.relkind != 'l' and not i.indisprimary",
2039 2040
			g_last_builtin_oid);

Bruce Momjian's avatar
Bruce Momjian committed
2041
	res = PQexec(g_conn, query->data);
2042 2043 2044
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
2045
		fprintf(stderr, "getIndices(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
2046 2047 2048 2049 2050 2051 2052 2053 2054
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numIndices = ntups;

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

2055 2056
	memset((char *) indinfo, 0, ntups * sizeof(IndInfo));

2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
	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));
2071 2072 2073 2074 2075 2076
		parseNumericArray(PQgetvalue(res, i, i_indkey),
						  indinfo[i].indkey,
						  INDEX_MAX_KEYS);
		parseNumericArray(PQgetvalue(res, i, i_indclass),
						  indinfo[i].indclass,
						  INDEX_MAX_KEYS);
2077 2078 2079 2080
		indinfo[i].indisunique = strdup(PQgetvalue(res, i, i_indisunique));
	}
	PQclear(res);
	return indinfo;
2081 2082 2083 2084
}

/*
 * dumpTypes
2085
 *	  writes out to fout the queries to recreate all the user-defined types
2086 2087 2088
 *
 */
void
2089 2090
dumpTypes(FILE *fout, FuncInfo *finfo, int numFuncs,
		  TypeInfo *tinfo, int numTypes)
2091
{
2092
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
2093
	PQExpBuffer	q = createPQExpBuffer();
2094
	int			funcInd;
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

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

2124
		becomeUser(fout, tinfo[i].usename);
2125

2126
		if (dropSchema)
Bruce Momjian's avatar
Bruce Momjian committed
2127
		{
Bruce Momjian's avatar
Bruce Momjian committed
2128 2129 2130
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "DROP TYPE %s;\n", fmtId(tinfo[i].typname, force_quotes));
			fputs(q->data, fout);
Bruce Momjian's avatar
Bruce Momjian committed
2131
		}
2132

Bruce Momjian's avatar
Bruce Momjian committed
2133 2134
		resetPQExpBuffer(q);
		appendPQExpBuffer(q,
2135
				"CREATE TYPE %s "
2136 2137
				"( internallength = %s, externallength = %s, input = %s, "
				"output = %s, send = %s, receive = %s, default = '%s'",
2138
				fmtId(tinfo[i].typname, force_quotes),
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
				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)
		{
2149
			char	   *elemType;
2150 2151 2152

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

Bruce Momjian's avatar
Bruce Momjian committed
2153 2154
			appendPQExpBuffer(q, ", element = %s, delimiter = '%s'",
					elemType, tinfo[i].typdelim);
2155 2156
		}
		if (tinfo[i].passedbyvalue)
Bruce Momjian's avatar
Bruce Momjian committed
2157
			appendPQExpBuffer(q, ",passedbyvalue);\n");
2158
		else
Bruce Momjian's avatar
Bruce Momjian committed
2159
			appendPQExpBuffer(q, ");\n");
2160

Bruce Momjian's avatar
Bruce Momjian committed
2161
		fputs(q->data, fout);
2162
	}
2163 2164
}

2165 2166
/*
 * dumpProcLangs
Bruce Momjian's avatar
Bruce Momjian committed
2167
 *		  writes out to fout the queries to recreate user-defined procedural languages
2168 2169 2170 2171
 *
 */
void
dumpProcLangs(FILE *fout, FuncInfo *finfo, int numFuncs,
Bruce Momjian's avatar
Bruce Momjian committed
2172
			  TypeInfo *tinfo, int numTypes)
2173
{
Bruce Momjian's avatar
Bruce Momjian committed
2174 2175
	PGresult	*res;
	PQExpBuffer	query = createPQExpBuffer();
2176 2177 2178 2179 2180
	int			ntups;
	int			i_lanname;
	int			i_lanpltrusted;
	int			i_lanplcallfoid;
	int			i_lancompiler;
Bruce Momjian's avatar
Bruce Momjian committed
2181 2182 2183
	char		*lanname;
	char		*lancompiler;
	const char	*lanplcallfoid;
2184 2185 2186
	int			i,
				fidx;

Bruce Momjian's avatar
Bruce Momjian committed
2187
	appendPQExpBuffer(query, "SELECT * FROM pg_language "
2188 2189
			"WHERE lanispl "
			"ORDER BY oid");
Bruce Momjian's avatar
Bruce Momjian committed
2190
	res = PQexec(g_conn, query->data);
2191 2192 2193
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
2194
		fprintf(stderr, "dumpProcLangs(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
2195 2196 2197 2198
		exit_nicely(g_conn);
	}
	ntups = PQntuples(res);

Bruce Momjian's avatar
Bruce Momjian committed
2199 2200 2201 2202
	i_lanname = PQfnumber(res, "lanname");
	i_lanpltrusted = PQfnumber(res, "lanpltrusted");
	i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
	i_lancompiler = PQfnumber(res, "lancompiler");
2203

Bruce Momjian's avatar
Bruce Momjian committed
2204 2205
	for (i = 0; i < ntups; i++)
	{
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
		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));

2223
		if (dropSchema)
Bruce Momjian's avatar
Bruce Momjian committed
2224
			fprintf(fout, "DROP PROCEDURAL LANGUAGE '%s';\n", lanname);
2225

2226
		fprintf(fout, "CREATE %sPROCEDURAL LANGUAGE '%s' "
Bruce Momjian's avatar
Bruce Momjian committed
2227 2228 2229 2230 2231
				"HANDLER %s LANCOMPILER '%s';\n",
		(PQgetvalue(res, i, i_lanpltrusted)[0] == 't') ? "TRUSTED " : "",
				lanname,
				fmtId(finfo[fidx].proname, force_quotes),
				lancompiler);
2232 2233 2234 2235 2236 2237 2238 2239 2240

		free(lanname);
		free(lancompiler);
	}

	PQclear(res);

}

2241 2242
/*
 * dumpFuncs
2243
 *	  writes out to fout the queries to recreate all the user-defined functions
2244 2245 2246
 *
 */
void
2247 2248
dumpFuncs(FILE *fout, FuncInfo *finfo, int numFuncs,
		  TypeInfo *tinfo, int numTypes)
2249
{
2250
	int			i;
2251 2252 2253

	for (i = 0; i < numFuncs; i++)
		dumpOneFunc(fout, finfo, i, tinfo, numTypes);
2254 2255 2256 2257
}

/*
 * dumpOneFunc:
2258 2259
 *	  dump out only one function,  the index of which is given in the third
 *	argument
2260 2261 2262
 *
 */

2263
static void
2264 2265
dumpOneFunc(FILE *fout, FuncInfo *finfo, int i,
			TypeInfo *tinfo, int numTypes)
2266
{
Bruce Momjian's avatar
Bruce Momjian committed
2267
	PQExpBuffer	q = createPQExpBuffer();
Bruce Momjian's avatar
Bruce Momjian committed
2268
	int			j;
Bruce Momjian's avatar
Bruce Momjian committed
2269
	char		*func_def;
2270
	char		func_lang[NAMEDATALEN + 1];
2271 2272 2273 2274 2275 2276

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

2277
	becomeUser(fout, finfo[i].usename);
2278

2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
	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
	{
Bruce Momjian's avatar
Bruce Momjian committed
2296 2297 2298
		PGresult   *res;
		int			nlangs;
		int			i_lanname;
2299 2300 2301
		char		query[256];

		sprintf(query, "SELECT lanname FROM pg_language "
2302
				"WHERE oid = %u",
2303 2304 2305 2306 2307
				finfo[i].lang);
		res = PQexec(g_conn, query);
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
2308
			fprintf(stderr, "dumpOneFunc(): SELECT for procedural language failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
			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);

	}

2328
	if (dropSchema)
Bruce Momjian's avatar
Bruce Momjian committed
2329
	{
Bruce Momjian's avatar
Bruce Momjian committed
2330 2331
		resetPQExpBuffer(q);
		appendPQExpBuffer(q, "DROP FUNCTION %s (", fmtId(finfo[i].proname, force_quotes));
Bruce Momjian's avatar
Bruce Momjian committed
2332 2333 2334 2335 2336
		for (j = 0; j < finfo[i].nargs; j++)
		{
			char	   *typname;

			typname = findTypeByOid(tinfo, numTypes, finfo[i].argtypes[j]);
Bruce Momjian's avatar
Bruce Momjian committed
2337
			appendPQExpBuffer(q, "%s%s",
Bruce Momjian's avatar
Bruce Momjian committed
2338 2339 2340
					(j > 0) ? "," : "",
					fmtId(typname, false));
		}
Bruce Momjian's avatar
Bruce Momjian committed
2341 2342
		appendPQExpBuffer(q, ");\n");
		fputs(q->data, fout);
Bruce Momjian's avatar
Bruce Momjian committed
2343
	}
2344

Bruce Momjian's avatar
Bruce Momjian committed
2345 2346
	resetPQExpBuffer(q);
	appendPQExpBuffer(q, "CREATE FUNCTION %s (", fmtId(finfo[i].proname, force_quotes));
2347 2348
	for (j = 0; j < finfo[i].nargs; j++)
	{
2349
		char	   *typname;
2350 2351

		typname = findTypeByOid(tinfo, numTypes, finfo[i].argtypes[j]);
Bruce Momjian's avatar
Bruce Momjian committed
2352
		appendPQExpBuffer(q, "%s%s",
2353
				(j > 0) ? "," : "",
2354
				fmtId(typname, false));
2355
	}
Bruce Momjian's avatar
Bruce Momjian committed
2356
	appendPQExpBuffer(q, " ) RETURNS %s%s AS '%s' LANGUAGE '%s';\n",
2357
			(finfo[i].retset) ? " SETOF " : "",
Bruce Momjian's avatar
Bruce Momjian committed
2358
			fmtId(findTypeByOid(tinfo, numTypes, finfo[i].prorettype), false),
2359
			func_def, func_lang);
2360

Bruce Momjian's avatar
Bruce Momjian committed
2361
	fputs(q->data, fout);
2362 2363 2364 2365 2366

}

/*
 * dumpOprs
2367
 *	  writes out to fout the queries to recreate all the user-defined operators
2368 2369
 *
 */
2370
void
2371 2372
dumpOprs(FILE *fout, OprInfo *oprinfo, int numOperators,
		 TypeInfo *tinfo, int numTypes)
2373
{
Bruce Momjian's avatar
Bruce Momjian committed
2374
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
2375 2376 2377 2378 2379 2380 2381 2382 2383
	PQExpBuffer	q = createPQExpBuffer();
	PQExpBuffer	leftarg = createPQExpBuffer();
	PQExpBuffer	rightarg = createPQExpBuffer();
	PQExpBuffer	commutator = createPQExpBuffer();
	PQExpBuffer	negator = createPQExpBuffer();
	PQExpBuffer	restrictor = createPQExpBuffer();
	PQExpBuffer	join = createPQExpBuffer();
	PQExpBuffer	sort1 = createPQExpBuffer();
	PQExpBuffer	sort2 = createPQExpBuffer();
2384 2385 2386 2387

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

Bruce Momjian's avatar
Bruce Momjian committed
2388 2389 2390 2391 2392 2393 2394 2395 2396
		resetPQExpBuffer(leftarg);
		resetPQExpBuffer(rightarg);
		resetPQExpBuffer(commutator);
		resetPQExpBuffer(negator);
		resetPQExpBuffer(restrictor);
		resetPQExpBuffer(join);
		resetPQExpBuffer(sort1);
		resetPQExpBuffer(sort2);

2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414
		/* skip all the builtin oids */
		if (atoi(oprinfo[i].oid) < g_last_builtin_oid)
			continue;

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

		/*
		 * right unary means there's a left arg and left unary means
		 * there's a right arg
		 */
		if (strcmp(oprinfo[i].oprkind, "r") == 0 ||
			strcmp(oprinfo[i].oprkind, "b") == 0)
		{
Bruce Momjian's avatar
Bruce Momjian committed
2415
			appendPQExpBuffer(leftarg, ",\n\tLEFTARG = %s ",
Bruce Momjian's avatar
Bruce Momjian committed
2416
					fmtId(findTypeByOid(tinfo, numTypes, oprinfo[i].oprleft), false));
2417 2418 2419 2420
		}
		if (strcmp(oprinfo[i].oprkind, "l") == 0 ||
			strcmp(oprinfo[i].oprkind, "b") == 0)
		{
Bruce Momjian's avatar
Bruce Momjian committed
2421
			appendPQExpBuffer(rightarg, ",\n\tRIGHTARG = %s ",
Bruce Momjian's avatar
Bruce Momjian committed
2422
					fmtId(findTypeByOid(tinfo, numTypes, oprinfo[i].oprright), false));
2423
		}
Bruce Momjian's avatar
Bruce Momjian committed
2424 2425
		if (!(strcmp(oprinfo[i].oprcom, "0") == 0))
			appendPQExpBuffer(commutator, ",\n\tCOMMUTATOR = %s ",
2426 2427
				 findOprByOid(oprinfo, numOperators, oprinfo[i].oprcom));

Bruce Momjian's avatar
Bruce Momjian committed
2428 2429
		if (!(strcmp(oprinfo[i].oprnegate, "0") == 0))
			appendPQExpBuffer(negator, ",\n\tNEGATOR = %s ",
2430 2431
			  findOprByOid(oprinfo, numOperators, oprinfo[i].oprnegate));

Bruce Momjian's avatar
Bruce Momjian committed
2432 2433
		if (!(strcmp(oprinfo[i].oprrest, "-") == 0))
			appendPQExpBuffer(restrictor, ",\n\tRESTRICT = %s ", oprinfo[i].oprrest);
2434

Bruce Momjian's avatar
Bruce Momjian committed
2435 2436
		if (!(strcmp(oprinfo[i].oprjoin, "-") == 0))
			appendPQExpBuffer(join, ",\n\tJOIN = %s ", oprinfo[i].oprjoin);
2437

Bruce Momjian's avatar
Bruce Momjian committed
2438 2439
		if (!(strcmp(oprinfo[i].oprlsortop, "0") == 0))
			appendPQExpBuffer(sort1, ",\n\tSORT1 = %s ",
Bruce Momjian's avatar
Bruce Momjian committed
2440
			 findOprByOid(oprinfo, numOperators, oprinfo[i].oprlsortop));
2441

Bruce Momjian's avatar
Bruce Momjian committed
2442 2443
		if (!(strcmp(oprinfo[i].oprrsortop, "0") == 0))
			appendPQExpBuffer(sort2, ",\n\tSORT2 = %s ",
Bruce Momjian's avatar
Bruce Momjian committed
2444
			 findOprByOid(oprinfo, numOperators, oprinfo[i].oprrsortop));
2445

2446
		becomeUser(fout, oprinfo[i].usename);
2447

2448
		if (dropSchema)
Bruce Momjian's avatar
Bruce Momjian committed
2449
		{
Bruce Momjian's avatar
Bruce Momjian committed
2450 2451
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "DROP OPERATOR %s (%s, %s);\n", oprinfo[i].oprname,
Bruce Momjian's avatar
Bruce Momjian committed
2452 2453
					fmtId(findTypeByOid(tinfo, numTypes, oprinfo[i].oprleft), false),
					fmtId(findTypeByOid(tinfo, numTypes, oprinfo[i].oprright), false));
Bruce Momjian's avatar
Bruce Momjian committed
2454
			fputs(q->data, fout);
Bruce Momjian's avatar
Bruce Momjian committed
2455
		}
2456

Bruce Momjian's avatar
Bruce Momjian committed
2457 2458
		resetPQExpBuffer(q);
		appendPQExpBuffer(q,
2459
				"CREATE OPERATOR %s "
2460
				"(PROCEDURE = %s %s%s%s%s%s%s%s%s%s);\n",
2461 2462
				oprinfo[i].oprname,
				oprinfo[i].oprcode,
Bruce Momjian's avatar
Bruce Momjian committed
2463 2464 2465 2466 2467
				leftarg->data,
				rightarg->data,
				commutator->data,
				negator->data,
				restrictor->data,
Bruce Momjian's avatar
Bruce Momjian committed
2468
		  (strcmp(oprinfo[i].oprcanhash, "t") == 0) ? ",\n\tHASHES" : "",
Bruce Momjian's avatar
Bruce Momjian committed
2469 2470 2471
				join->data,
				sort1->data,
				sort2->data);
2472

Bruce Momjian's avatar
Bruce Momjian committed
2473
		fputs(q->data, fout);
2474
	}
2475 2476 2477 2478
}

/*
 * dumpAggs
2479
 *	  writes out to fout the queries to create all the user-defined aggregates
2480 2481 2482
 *
 */
void
2483 2484
dumpAggs(FILE *fout, AggInfo *agginfo, int numAggs,
		 TypeInfo *tinfo, int numTypes)
2485
{
Bruce Momjian's avatar
Bruce Momjian committed
2486
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
2487 2488 2489 2490 2491
	PQExpBuffer	q = createPQExpBuffer();
	PQExpBuffer	sfunc1 = createPQExpBuffer();
	PQExpBuffer	sfunc2 = createPQExpBuffer();
	PQExpBuffer	basetype = createPQExpBuffer();
	PQExpBuffer	finalfunc = createPQExpBuffer();
2492
	char		comma1[2],
Bruce Momjian's avatar
Bruce Momjian committed
2493
				comma2[2];
2494 2495 2496

	for (i = 0; i < numAggs; i++)
	{
Bruce Momjian's avatar
Bruce Momjian committed
2497 2498 2499 2500 2501 2502

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

2503 2504 2505
		/* skip all the builtin oids */
		if (atoi(agginfo[i].oid) < g_last_builtin_oid)
			continue;
2506

Bruce Momjian's avatar
Bruce Momjian committed
2507
		appendPQExpBuffer(basetype,
2508
				"BASETYPE = %s, ",
Bruce Momjian's avatar
Bruce Momjian committed
2509
				fmtId(findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype), false));
2510

Bruce Momjian's avatar
Bruce Momjian committed
2511
		if (!(strcmp(agginfo[i].aggtransfn1, "-") == 0))
2512
		{
Bruce Momjian's avatar
Bruce Momjian committed
2513
			appendPQExpBuffer(sfunc1,
2514
					"SFUNC1 = %s, STYPE1 = %s",
2515
					agginfo[i].aggtransfn1,
2516
					fmtId(findTypeByOid(tinfo, numTypes, agginfo[i].aggtranstype1), false));
2517
			if (agginfo[i].agginitval1)
Bruce Momjian's avatar
Bruce Momjian committed
2518 2519
				appendPQExpBuffer(sfunc1, ", INITCOND1 = '%s'",
						agginfo[i].agginitval1);
2520 2521 2522

		}

Bruce Momjian's avatar
Bruce Momjian committed
2523
		if (!(strcmp(agginfo[i].aggtransfn2, "-") == 0))
2524
		{
Bruce Momjian's avatar
Bruce Momjian committed
2525
			appendPQExpBuffer(sfunc2,
2526 2527
					"SFUNC2 = %s, STYPE2 = %s",
					agginfo[i].aggtransfn2,
2528
					fmtId(findTypeByOid(tinfo, numTypes, agginfo[i].aggtranstype2), false));
2529
			if (agginfo[i].agginitval2)
Bruce Momjian's avatar
Bruce Momjian committed
2530 2531
				appendPQExpBuffer(sfunc2, ", INITCOND2 = '%s'",
						agginfo[i].agginitval2);
2532 2533
		}

Bruce Momjian's avatar
Bruce Momjian committed
2534 2535 2536
		if (!(strcmp(agginfo[i].aggfinalfn, "-") == 0))
			appendPQExpBuffer(finalfunc, "FINALFUNC = %s", agginfo[i].aggfinalfn);
		if (sfunc1->data[0] != '\0' && sfunc2->data[0] != '\0')
2537 2538 2539 2540 2541 2542 2543
		{
			comma1[0] = ',';
			comma1[1] = '\0';
		}
		else
			comma1[0] = '\0';

Bruce Momjian's avatar
Bruce Momjian committed
2544
		if (finalfunc->data[0] != '\0' && (sfunc1->data[0] != '\0' || sfunc2->data[0] != '\0'))
2545 2546 2547 2548 2549 2550 2551
		{
			comma2[0] = ',';
			comma2[1] = '\0';
		}
		else
			comma2[0] = '\0';

2552
		becomeUser(fout, agginfo[i].usename);
2553

2554
		if (dropSchema)
Bruce Momjian's avatar
Bruce Momjian committed
2555
		{
Bruce Momjian's avatar
Bruce Momjian committed
2556 2557
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "DROP AGGREGATE %s %s;\n", agginfo[i].aggname,
Bruce Momjian's avatar
Bruce Momjian committed
2558
					fmtId(findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype), false));
Bruce Momjian's avatar
Bruce Momjian committed
2559
			fputs(q->data, fout);
Bruce Momjian's avatar
Bruce Momjian committed
2560
		}
2561

Bruce Momjian's avatar
Bruce Momjian committed
2562 2563
		resetPQExpBuffer(q);
		appendPQExpBuffer(q, "CREATE AGGREGATE %s ( %s %s%s %s%s %s );\n",
2564
				agginfo[i].aggname,
Bruce Momjian's avatar
Bruce Momjian committed
2565 2566
				basetype->data,
				sfunc1->data,
2567
				comma1,
Bruce Momjian's avatar
Bruce Momjian committed
2568
				sfunc2->data,
2569
				comma2,
Bruce Momjian's avatar
Bruce Momjian committed
2570
				finalfunc->data);
2571

Bruce Momjian's avatar
Bruce Momjian committed
2572
		fputs(q->data, fout);
2573
	}
2574 2575
}

2576 2577 2578 2579 2580
/*
 * These are some support functions to fix the acl problem of pg_dump
 *
 * Matthew C. Aycock 12/02/97
 */
2581 2582 2583

/* Append a keyword to a keyword list, inserting comma if needed.
 * Caller must make aclbuf big enough for all possible keywords.
2584
 */
2585
static void
Bruce Momjian's avatar
Bruce Momjian committed
2586
AddAcl(char *aclbuf, const char *keyword)
2587
{
2588 2589 2590
	if (*aclbuf)
		strcat(aclbuf, ",");
	strcat(aclbuf, keyword);
2591
}
2592

2593
/*
2594
 * This will take a string of 'arwR' and return a malloced,
2595 2596
 * comma delimited string of SELECT,INSERT,UPDATE,DELETE,RULE
 */
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
2597
static char *
2598
GetPrivileges(const char *s)
2599
{
2600
	char		aclbuf[100];
2601

2602
	aclbuf[0] = '\0';
2603

Bruce Momjian's avatar
Bruce Momjian committed
2604
	if (strchr(s, 'a'))
2605
		AddAcl(aclbuf, "INSERT");
2606

Bruce Momjian's avatar
Bruce Momjian committed
2607
	if (strchr(s, 'w'))
2608
		AddAcl(aclbuf, "UPDATE,DELETE");
Bruce Momjian's avatar
Bruce Momjian committed
2609 2610

	if (strchr(s, 'r'))
2611
		AddAcl(aclbuf, "SELECT");
2612

2613
	if (strchr(s, 'R'))
2614
		AddAcl(aclbuf, "RULE");
2615

2616 2617 2618
	/* Special-case when they're all there */
	if (strcmp(aclbuf, "INSERT,UPDATE,DELETE,SELECT,RULE") == 0)
		return strdup("ALL");
2619

2620
	return strdup(aclbuf);
2621
}
2622

Bruce Momjian's avatar
Bruce Momjian committed
2623 2624
/*
 * dumpACL:
2625 2626
 *	  Write out grant/revoke information
 *	  Called for sequences and tables
Bruce Momjian's avatar
Bruce Momjian committed
2627 2628
 */

2629
static void
Bruce Momjian's avatar
Bruce Momjian committed
2630 2631
dumpACL(FILE *fout, TableInfo tbinfo)
{
2632 2633
	const char *acls = tbinfo.relacl;
	char	   *aclbuf,
Bruce Momjian's avatar
Bruce Momjian committed
2634 2635 2636
			   *tok,
			   *eqpos,
			   *priv;
2637 2638 2639 2640

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

Bruce Momjian's avatar
Bruce Momjian committed
2641 2642 2643
	/*
	 * Revoke Default permissions for PUBLIC. Is this actually necessary,
	 * or is it just a waste of time?
2644 2645 2646
	 */
	fprintf(fout,
			"REVOKE ALL on %s from PUBLIC;\n",
2647
			fmtId(tbinfo.relname, force_quotes));
2648 2649 2650

	/* Make a working copy of acls so we can use strtok */
	aclbuf = strdup(acls);
Bruce Momjian's avatar
Bruce Momjian committed
2651

2652 2653
	/* Scan comma-separated ACL items */
	for (tok = strtok(aclbuf, ","); tok != NULL; tok = strtok(NULL, ","))
2654
	{
Bruce Momjian's avatar
Bruce Momjian committed
2655 2656 2657
		/*
		 * Token may start with '{' and/or '"'.  Actually only the start
		 * of the string should have '{', but we don't verify that.
2658 2659 2660 2661 2662 2663 2664 2665
		 */
		if (*tok == '{')
			tok++;
		if (*tok == '"')
			tok++;

		/* User name is string up to = in tok */
		eqpos = strchr(tok, '=');
Bruce Momjian's avatar
Bruce Momjian committed
2666
		if (!eqpos)
Bruce Momjian's avatar
Bruce Momjian committed
2667
		{
2668
			fprintf(stderr, "Could not parse ACL list for '%s'...Exiting!\n",
Bruce Momjian's avatar
Bruce Momjian committed
2669 2670 2671 2672
					tbinfo.relname);
			exit_nicely(g_conn);
		}

Bruce Momjian's avatar
Bruce Momjian committed
2673 2674 2675 2676
		/*
		 * Parse the privileges (right-hand side).	Skip if there are
		 * none.
		 */
2677 2678
		priv = GetPrivileges(eqpos + 1);
		if (*priv)
2679
		{
2680 2681
			fprintf(fout,
					"GRANT %s on %s to ",
2682
					priv, fmtId(tbinfo.relname, force_quotes));
Bruce Momjian's avatar
Bruce Momjian committed
2683 2684 2685

			/*
			 * Note: fmtId() can only be called once per printf, so don't
2686 2687 2688 2689 2690
			 * try to merge printing of username into the above printf.
			 */
			if (eqpos == tok)
			{
				/* Empty left-hand side means "PUBLIC" */
2691
				fprintf(fout, "PUBLIC;\n");
2692
			}
2693
			else
2694 2695
			{
				*eqpos = '\0';	/* it's ok to clobber aclbuf */
2696 2697 2698 2699 2700
				if (strncmp(tok, "group ", strlen("group ")) == 0)
					fprintf(fout, "GROUP %s;\n",
							fmtId(tok + strlen("group "), force_quotes));
				else
					fprintf(fout, "%s;\n", fmtId(tok, force_quotes));
2701
			}
2702
		}
2703
		free(priv);
Bruce Momjian's avatar
Bruce Momjian committed
2704
	}
2705 2706

	free(aclbuf);
Bruce Momjian's avatar
Bruce Momjian committed
2707 2708
}

2709

2710 2711
/*
 * dumpTables:
2712
 *	  write out to fout all the user-define tables
2713
 */
2714

2715
void
2716 2717 2718
dumpTables(FILE *fout, TableInfo *tblinfo, int numTables,
		   InhInfo *inhinfo, int numInherits,
		   TypeInfo *tinfo, int numTypes, const char *tablename,
2719
		   const bool aclsSkip)
2720
{
2721 2722
	int			i,
				j,
Bruce Momjian's avatar
Bruce Momjian committed
2723
				k;
Bruce Momjian's avatar
Bruce Momjian committed
2724 2725
	PQExpBuffer	q = createPQExpBuffer();
	char		*serialSeq = NULL;		/* implicit sequence name created
Bruce Momjian's avatar
Bruce Momjian committed
2726 2727 2728 2729
										 * by SERIAL datatype */
	const char *serialSeqSuffix = "_id_seq";	/* suffix for implicit
												 * SERIAL sequences */
	char	  **parentRels;		/* list of names of parent relations */
2730
	int			numParents;
Bruce Momjian's avatar
Bruce Momjian committed
2731 2732
	int			actual_atts;	/* number of attrs in this CREATE statment */
	int32		tmp_typmod;
2733 2734 2735
	int			precision;
	int			scale;

2736

2737
	/* First - dump SEQUENCEs */
Bruce Momjian's avatar
Bruce Momjian committed
2738
	if (tablename)
Bruce Momjian's avatar
Bruce Momjian committed
2739 2740 2741 2742 2743
	{
		serialSeq = malloc(strlen(tablename) + strlen(serialSeqSuffix) + 1);
		strcpy(serialSeq, tablename);
		strcat(serialSeq, serialSeqSuffix);
	}
2744 2745 2746 2747
	for (i = 0; i < numTables; i++)
	{
		if (!(tblinfo[i].sequence))
			continue;
Bruce Momjian's avatar
Bruce Momjian committed
2748
		if (!tablename || (!strcmp(tblinfo[i].relname, tablename))
Bruce Momjian's avatar
Bruce Momjian committed
2749
			|| (serialSeq && !strcmp(tblinfo[i].relname, serialSeq)))
2750
		{
2751
			becomeUser(fout, tblinfo[i].usename);
2752
			dumpSequence(fout, tblinfo[i]);
2753
			if (!aclsSkip)
Bruce Momjian's avatar
Bruce Momjian committed
2754
				dumpACL(fout, tblinfo[i]);
2755 2756
		}
	}
Bruce Momjian's avatar
Bruce Momjian committed
2757
	if (tablename)
Bruce Momjian's avatar
Bruce Momjian committed
2758
		free(serialSeq);
2759

2760 2761
	for (i = 0; i < numTables; i++)
	{
2762
		if (tblinfo[i].sequence)/* already dumped */
2763
			continue;
2764 2765 2766 2767

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

2768
			/* Skip VIEW relations */
Bruce Momjian's avatar
Bruce Momjian committed
2769

2770
			/*
Bruce Momjian's avatar
Bruce Momjian committed
2771 2772
			 * if (isViewRule(tblinfo[i].relname)) continue;
			 */
2773

2774 2775
			parentRels = tblinfo[i].parentRels;
			numParents = tblinfo[i].numParents;
2776

2777
			becomeUser(fout, tblinfo[i].usename);
2778

2779
			if (dropSchema)
Bruce Momjian's avatar
Bruce Momjian committed
2780
			{
Bruce Momjian's avatar
Bruce Momjian committed
2781 2782 2783
				resetPQExpBuffer(q);
				appendPQExpBuffer(q, "DROP TABLE %s;\n", fmtId(tblinfo[i].relname, force_quotes));
				fputs(q->data, fout);
Bruce Momjian's avatar
Bruce Momjian committed
2784
			}
2785

Bruce Momjian's avatar
Bruce Momjian committed
2786 2787
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "CREATE TABLE %s (\n\t", fmtId(tblinfo[i].relname, force_quotes));
2788 2789 2790 2791
			actual_atts = 0;
			for (j = 0; j < tblinfo[i].numatts; j++)
			{
				if (tblinfo[i].inhAttrs[j] == 0)
Bruce Momjian's avatar
Bruce Momjian committed
2792
				{
2793
					if (actual_atts > 0)
Bruce Momjian's avatar
Bruce Momjian committed
2794 2795
						appendPQExpBuffer(q, ",\n\t");
					appendPQExpBuffer(q, "%s ",
2796
							fmtId(tblinfo[i].attnames[j], force_quotes));
2797 2798 2799

					/* Show lengths on bpchar and varchar */
					if (!strcmp(tblinfo[i].typnames[j], "bpchar"))
2800
					{
Bruce Momjian's avatar
Bruce Momjian committed
2801 2802
						int			len = (tblinfo[i].atttypmod[j] - VARHDRSZ);

Bruce Momjian's avatar
Bruce Momjian committed
2803
						appendPQExpBuffer(q, "character");
2804
						if (len > 1)
Bruce Momjian's avatar
Bruce Momjian committed
2805
							appendPQExpBuffer(q, "(%d)",
2806
									tblinfo[i].atttypmod[j] - VARHDRSZ);
2807
					}
2808 2809
					else if (!strcmp(tblinfo[i].typnames[j], "varchar"))
					{
Bruce Momjian's avatar
Bruce Momjian committed
2810
						appendPQExpBuffer(q, "character varying");
2811 2812
						if (tblinfo[i].atttypmod[j] != -1)
						{
Bruce Momjian's avatar
Bruce Momjian committed
2813
							appendPQExpBuffer(q, "(%d)",
2814
									tblinfo[i].atttypmod[j] - VARHDRSZ);
2815
						}
2816
					}
2817 2818
					else if (!strcmp(tblinfo[i].typnames[j], "numeric"))
					{
Bruce Momjian's avatar
Bruce Momjian committed
2819
						appendPQExpBuffer(q, "numeric");
2820 2821 2822 2823
						if (tblinfo[i].atttypmod[j] != -1)
						{
							tmp_typmod = tblinfo[i].atttypmod[j] - VARHDRSZ;
							precision = (tmp_typmod >> 16) & 0xffff;
Bruce Momjian's avatar
Bruce Momjian committed
2824
							scale = tmp_typmod & 0xffff;
Bruce Momjian's avatar
Bruce Momjian committed
2825
							appendPQExpBuffer(q, "(%d,%d)",
Bruce Momjian's avatar
Bruce Momjian committed
2826
									precision, scale);
2827 2828
						}
					}
Bruce Momjian's avatar
Bruce Momjian committed
2829 2830 2831 2832 2833

					/*
					 * char is an internal single-byte data type; Let's
					 * make sure we force it through with quotes. - thomas
					 * 1998-12-13
2834 2835 2836
					 */
					else if (!strcmp(tblinfo[i].typnames[j], "char"))
					{
Bruce Momjian's avatar
Bruce Momjian committed
2837
						appendPQExpBuffer(q, "%s",
2838 2839
								fmtId(tblinfo[i].typnames[j], true));
					}
2840 2841
					else
					{
Bruce Momjian's avatar
Bruce Momjian committed
2842
						appendPQExpBuffer(q, "%s",
2843
								fmtId(tblinfo[i].typnames[j], false));
2844 2845
					}
					if (tblinfo[i].adef_expr[j] != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
2846
						appendPQExpBuffer(q, " DEFAULT %s",
2847
								tblinfo[i].adef_expr[j]);
2848
					if (tblinfo[i].notnull[j])
Bruce Momjian's avatar
Bruce Momjian committed
2849
						appendPQExpBuffer(q, " NOT NULL");
2850
					actual_atts++;
2851
				}
2852
			}
Bruce Momjian's avatar
Bruce Momjian committed
2853

2854 2855 2856
			/* put the CONSTRAINTS inside the table def */
			for (k = 0; k < tblinfo[i].ncheck; k++)
			{
2857
				if (actual_atts + k > 0)
Bruce Momjian's avatar
Bruce Momjian committed
2858 2859
					appendPQExpBuffer(q, ",\n\t");
				appendPQExpBuffer(q, "%s",
2860 2861
						tblinfo[i].check_expr[k]);
			}
2862

2863 2864 2865 2866 2867 2868
	    /* PRIMARY KEY */
	    if (tblinfo[i].primary_key) {
		if (actual_atts + tblinfo[i].ncheck > 0)
		    appendPQExpBuffer(q, ",\n\t");
		appendPQExpBuffer(q, "PRIMARY KEY (%s)", tblinfo[i].primary_key);
	    }
Bruce Momjian's avatar
Bruce Momjian committed
2869

2870
	    appendPQExpBuffer(q, "\n)");
2871 2872 2873

			if (numParents > 0)
			{
Bruce Momjian's avatar
Bruce Momjian committed
2874
				appendPQExpBuffer(q, "\ninherits (");
2875
				for (k = 0; k < numParents; k++)
Bruce Momjian's avatar
Bruce Momjian committed
2876
				{
Bruce Momjian's avatar
Bruce Momjian committed
2877
					appendPQExpBuffer(q, "%s%s",
2878
							(k > 0) ? ", " : "",
2879
							fmtId(parentRels[k], force_quotes));
Bruce Momjian's avatar
Bruce Momjian committed
2880
				}
Bruce Momjian's avatar
Bruce Momjian committed
2881
				appendPQExpBuffer(q, ")");
2882
			}
Bruce Momjian's avatar
Bruce Momjian committed
2883

Bruce Momjian's avatar
Bruce Momjian committed
2884 2885
			appendPQExpBuffer(q, ";\n");
			fputs(q->data, fout);
2886
			if (!aclsSkip)
Bruce Momjian's avatar
Bruce Momjian committed
2887
				dumpACL(fout, tblinfo[i]);
2888

2889 2890
		}
	}
2891 2892 2893 2894
}

/*
 * dumpIndices:
2895
 *	  write out to fout all the user-define indices
2896
 */
2897
void
2898 2899
dumpIndices(FILE *fout, IndInfo *indinfo, int numIndices,
			TableInfo *tblinfo, int numTables, const char *tablename)
2900
{
2901 2902 2903
	int			i,
				k;
	int			tableInd;
Bruce Momjian's avatar
Bruce Momjian committed
2904
	PQExpBuffer	attlist = createPQExpBuffer();
Bruce Momjian's avatar
Bruce Momjian committed
2905 2906 2907
	char	   *classname[INDEX_MAX_KEYS];
	char	   *funcname;		/* the name of the function to comput the
								 * index key from */
2908 2909 2910
	int			indkey,
				indclass;
	int			nclass;
2911

Bruce Momjian's avatar
Bruce Momjian committed
2912 2913 2914
	PQExpBuffer	q = createPQExpBuffer(),
				id1 = createPQExpBuffer(),
				id2 = createPQExpBuffer();
2915
	PGresult   *res;
2916 2917 2918 2919

	for (i = 0; i < numIndices; i++)
	{
		tableInd = findTableByName(tblinfo, numTables,
2920 2921 2922 2923 2924 2925 2926
								   indinfo[i].indrelname);
		if (tableInd < 0)
		{
			fprintf(stderr, "failed sanity check, table %s was not found\n",
					indinfo[i].indrelname);
			exit(2);
		}
2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938

		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*
			 */
Bruce Momjian's avatar
Bruce Momjian committed
2939 2940
			resetPQExpBuffer(q);
			appendPQExpBuffer(q,
2941 2942 2943
					"SELECT proname from pg_proc "
					"where pg_proc.oid = '%s'::oid",
					indinfo[i].indproc);
Bruce Momjian's avatar
Bruce Momjian committed
2944
			res = PQexec(g_conn, q->data);
2945 2946
			if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
			{
2947
				fprintf(stderr, "dumpIndices(): SELECT (funcname) failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
				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;
Bruce Momjian's avatar
Bruce Momjian committed
2961 2962
			resetPQExpBuffer(q);
			appendPQExpBuffer(q,
2963 2964 2965
					"SELECT opcname from pg_opclass "
					"where pg_opclass.oid = '%u'::oid",
					indclass);
Bruce Momjian's avatar
Bruce Momjian committed
2966
			res = PQexec(g_conn, q->data);
2967 2968
			if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
			{
2969
				fprintf(stderr, "dumpIndices(): SELECT (classname) failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984
				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 */
Bruce Momjian's avatar
Bruce Momjian committed
2985 2986
		resetPQExpBuffer(attlist);
		for (k = 0; k < INDEX_MAX_KEYS; k++)
2987
		{
2988
			char	   *attname;
2989 2990

			indkey = atoi(indinfo[i].indkey[k]);
Bruce Momjian's avatar
Bruce Momjian committed
2991
			if (indkey == InvalidAttrNumber)
2992 2993 2994 2995 2996 2997 2998
				break;
			indkey--;
			if (indkey == ObjectIdAttributeNumber - 1)
				attname = "oid";
			else
				attname = tblinfo[tableInd].attnames[indkey];
			if (funcname)
Bruce Momjian's avatar
Bruce Momjian committed
2999
				appendPQExpBuffer(attlist, "%s%s",
Bruce Momjian's avatar
Bruce Momjian committed
3000
					 (k == 0) ? "" : ", ", fmtId(attname, force_quotes));
3001 3002 3003 3004 3005
			else
			{
				if (k >= nclass)
				{
					fprintf(stderr, "dumpIndices(): OpClass not found for "
3006
							"attribute '%s' of index '%s'\n",
3007 3008 3009
							attname, indinfo[i].indexrelname);
					exit_nicely(g_conn);
				}
Bruce Momjian's avatar
Bruce Momjian committed
3010 3011 3012 3013 3014 3015
				resetPQExpBuffer(id1);
				resetPQExpBuffer(id2);
				appendPQExpBuffer(id1, fmtId(attname, force_quotes));
				appendPQExpBuffer(id2, fmtId(classname[k], force_quotes));
				appendPQExpBuffer(attlist, "%s%s %s",
						(k == 0) ? "" : ", ", id1->data, id2->data);
3016 3017 3018 3019 3020 3021
				free(classname[k]);
			}
		}

		if (!tablename || (!strcmp(indinfo[i].indrelname, tablename)))
		{
Bruce Momjian's avatar
Bruce Momjian committed
3022 3023 3024 3025 3026

			/*
			 * 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.
3027 3028
			 */
			becomeUser(fout, tblinfo[tableInd].usename);
3029

Bruce Momjian's avatar
Bruce Momjian committed
3030 3031 3032 3033
			resetPQExpBuffer(id1);
			resetPQExpBuffer(id2);
			appendPQExpBuffer(id1, fmtId(indinfo[i].indexrelname, force_quotes));
			appendPQExpBuffer(id2, fmtId(indinfo[i].indrelname, force_quotes));
3034

3035
			if (dropSchema)
Bruce Momjian's avatar
Bruce Momjian committed
3036
			{
Bruce Momjian's avatar
Bruce Momjian committed
3037 3038 3039
				resetPQExpBuffer(q);
				appendPQExpBuffer(q, "DROP INDEX %s;\n", id1->data);
				fputs(q->data, fout);
Bruce Momjian's avatar
Bruce Momjian committed
3040
			}
3041

3042
			fprintf(fout, "CREATE %s INDEX %s on %s using %s (",
3043
			  (strcmp(indinfo[i].indisunique, "t") == 0) ? "UNIQUE" : "",
Bruce Momjian's avatar
Bruce Momjian committed
3044 3045
					id1->data,
					id2->data,
3046 3047 3048
					indinfo[i].indamname);
			if (funcname)
			{
3049
				/* need 2 printf's here cuz fmtId has static return area */
3050
				fprintf(fout, " %s", fmtId(funcname, false));
Bruce Momjian's avatar
Bruce Momjian committed
3051
				fprintf(fout, " (%s) %s );\n", attlist->data, fmtId(classname[0], force_quotes));
3052 3053 3054 3055
				free(funcname);
				free(classname[0]);
			}
			else
Bruce Momjian's avatar
Bruce Momjian committed
3056
				fprintf(fout, " %s );\n", attlist->data);
3057 3058
		}
	}
3059 3060

}
3061

3062
/*
Bruce Momjian's avatar
Bruce Momjian committed
3063
 * dumpTuples
3064 3065 3066 3067 3068
 *	  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
3069
 *	  in PostgreSQL.
3070 3071 3072 3073
 *
 * the attrmap passed in tells how to map the attributes copied in to the
 * attributes copied out
 */
3074
#ifdef NOT_USED
3075
void
3076
dumpTuples(PGresult *res, FILE *fout, int *attrmap)
3077
{
3078 3079 3080 3081
	int			j,
				k;
	int			m,
				n;
Bruce Momjian's avatar
Bruce Momjian committed
3082
	char	  **outVals = NULL; /* values to copy out */
3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101

	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++)
			{
3102
				char	   *pval = outVals[k];
3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122

				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);
	}
3123
}
3124

3125
#endif
3126

3127 3128 3129 3130
/*
 * setMaxOid -
 * find the maximum oid and generate a COPY statement to set it
*/
3131

3132
static void
3133
setMaxOid(FILE *fout)
3134
{
Bruce Momjian's avatar
Bruce Momjian committed
3135
	PGresult   *res;
3136
	Oid			max_oid;
3137 3138 3139 3140 3141

	res = PQexec(g_conn, "CREATE TABLE pgdump_oid (dummy int4)");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
3142
		fprintf(stderr, "Can not create pgdump_oid table.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
3143 3144 3145 3146 3147 3148 3149
		exit_nicely(g_conn);
	}
	PQclear(res);
	res = PQexec(g_conn, "INSERT INTO pgdump_oid VALUES (0)");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
3150
		fprintf(stderr, "Can not insert into pgdump_oid table.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163
		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)
	{
3164
		fprintf(stderr, "Can not drop pgdump_oid table.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
3165 3166 3167 3168
		exit_nicely(g_conn);
	}
	PQclear(res);
	if (g_verbose)
3169
		fprintf(stderr, "%s maximum system oid is %u %s\n",
3170 3171 3172 3173 3174 3175 3176
				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");
}
3177 3178 3179

/*
 * findLastBuiltInOid -
3180
 * find the last built in oid
3181
 * we do this by looking up the oid of 'template1' in pg_database,
3182
 * this is probably not foolproof but comes close
3183 3184
*/

3185
static int
3186
findLastBuiltinOid(void)
3187
{
Bruce Momjian's avatar
Bruce Momjian committed
3188
	PGresult   *res;
3189 3190
	int			ntups;
	int			last_oid;
3191 3192 3193 3194 3195 3196

	res = PQexec(g_conn,
			  "SELECT oid from pg_database where datname = 'template1'");
	if (res == NULL ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
3197 3198
		fprintf(stderr,"pg_dump error in finding the template1 database.");
		fprintf(stderr,"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
3199 3200 3201
		exit_nicely(g_conn);
	}
	ntups = PQntuples(res);
3202
	if (ntups < 1)
3203
	{
3204
		fprintf(stderr,"pg_dump: couldn't find the template1 database.\n");
3205 3206 3207 3208 3209 3210 3211
		fprintf(stderr,"There is no 'template1' entry in the 'pg_database' table.\n");
		exit_nicely(g_conn);
	}
	if (ntups > 1)
	{
		fprintf(stderr,"pg_dump: found more than one template1 database.\n");
		fprintf(stderr,"There is more than one 'template1' entry in the 'pg_database' table\n");
3212 3213 3214 3215 3216
		exit_nicely(g_conn);
	}
	last_oid = atoi(PQgetvalue(res, 0, PQfnumber(res, "oid")));
	PQclear(res);
	return last_oid;
3217 3218 3219 3220 3221
}


/*
 * checkForQuote:
3222
 *	  checks a string for quote characters and quotes them
3223
 */
3224
static char *
3225
checkForQuote(const char *s)
3226
{
Bruce Momjian's avatar
Bruce Momjian committed
3227
	char	   *r;
3228
	char		c;
Bruce Momjian's avatar
Bruce Momjian committed
3229
	char	   *result;
3230

3231
	int			j = 0;
3232

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

3235 3236
	while ((c = *s) != '\0')
	{
3237

3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248
		if (c == '\'')
		{
			r[j++] = '\'';		/* quote the single quotes */
		}
		r[j++] = c;
		s++;
	}
	r[j] = '\0';

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

3250
	return result;
3251 3252

}
3253 3254


3255
static void
3256
dumpSequence(FILE *fout, TableInfo tbinfo)
3257
{
Bruce Momjian's avatar
Bruce Momjian committed
3258
	PGresult	*res;
Bruce Momjian's avatar
Bruce Momjian committed
3259
	int4		last,
3260 3261 3262 3263
				incby,
				maxv,
				minv,
				cache;
Bruce Momjian's avatar
Bruce Momjian committed
3264
	char		cycled,
Bruce Momjian's avatar
Bruce Momjian committed
3265
				called;
Bruce Momjian's avatar
Bruce Momjian committed
3266 3267
    const char	*t;
	PQExpBuffer	query = createPQExpBuffer();
3268

Bruce Momjian's avatar
Bruce Momjian committed
3269
	appendPQExpBuffer(query,
3270
			"SELECT sequence_name, last_value, increment_by, max_value, "
3271
			"min_value, cache_value, is_cycled, is_called from %s",
3272
			fmtId(tbinfo.relname, force_quotes));
3273

Bruce Momjian's avatar
Bruce Momjian committed
3274
	res = PQexec(g_conn, query->data);
3275 3276
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
3277
		fprintf(stderr, "dumpSequence(%s): SELECT failed.  Explanation from backend: '%s'.\n", tbinfo.relname, PQerrorMessage(g_conn));
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
		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);

3309
	if (dropSchema)
Bruce Momjian's avatar
Bruce Momjian committed
3310
	{
Bruce Momjian's avatar
Bruce Momjian committed
3311 3312 3313
		resetPQExpBuffer(query);
		appendPQExpBuffer(query, "DROP SEQUENCE %s;\n", fmtId(tbinfo.relname, force_quotes));
		fputs(query->data, fout);
Bruce Momjian's avatar
Bruce Momjian committed
3314
	}
3315

Bruce Momjian's avatar
Bruce Momjian committed
3316 3317
	resetPQExpBuffer(query);
	appendPQExpBuffer(query,
3318
			"CREATE SEQUENCE %s start %d increment %d maxvalue %d "
3319
			"minvalue %d  cache %d %s;\n",
Bruce Momjian's avatar
Bruce Momjian committed
3320
	 fmtId(tbinfo.relname, force_quotes), last, incby, maxv, minv, cache,
3321 3322
			(cycled == 't') ? "cycle" : "");

Bruce Momjian's avatar
Bruce Momjian committed
3323
	fputs(query->data, fout);
3324 3325 3326 3327

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

Bruce Momjian's avatar
Bruce Momjian committed
3328 3329 3330
	resetPQExpBuffer(query);
	appendPQExpBuffer(query, "SELECT nextval ('%s');\n", fmtId(tbinfo.relname, force_quotes));
	fputs(query->data, fout);
3331 3332

}
3333 3334


3335 3336 3337
static void
dumpTriggers(FILE *fout, const char *tablename,
			 TableInfo *tblinfo, int numTables)
3338
{
3339 3340 3341
	int			i,
				j;

3342 3343 3344
	if (g_verbose)
		fprintf(stderr, "%s dumping out triggers %s\n",
				g_comment_start, g_comment_end);
3345

3346 3347 3348 3349 3350 3351
	for (i = 0; i < numTables; i++)
	{
		if (tablename && strcmp(tblinfo[i].relname, tablename))
			continue;
		for (j = 0; j < tblinfo[i].ntrig; j++)
		{
3352
			becomeUser(fout, tblinfo[i].usename);
3353 3354 3355 3356
			fputs(tblinfo[i].triggers[j], fout);
		}
	}
}
3357 3358


3359 3360
static void
dumpRules(FILE *fout, const char *tablename,
Bruce Momjian's avatar
Bruce Momjian committed
3361
		  TableInfo *tblinfo, int numTables)
3362
{
Bruce Momjian's avatar
Bruce Momjian committed
3363 3364 3365 3366
	PGresult   *res;
	int			nrules;
	int			i,
				t;
Bruce Momjian's avatar
Bruce Momjian committed
3367
	PQExpBuffer	query = createPQExpBuffer();
3368

Bruce Momjian's avatar
Bruce Momjian committed
3369
	int			i_definition;
3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385

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

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

		/*
		 * Get all rules defined for this table
		 */
Bruce Momjian's avatar
Bruce Momjian committed
3386 3387
		resetPQExpBuffer(query);
		appendPQExpBuffer(query, "SELECT pg_get_ruledef(pg_rewrite.rulename) "
3388 3389 3390 3391 3392
				"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);
Bruce Momjian's avatar
Bruce Momjian committed
3393
		res = PQexec(g_conn, query->data);
3394 3395 3396
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
3397 3398
			fprintf(stderr, "dumpRules(): SELECT failed for table %s.  Explanation from backend: '%s'.\n",
					tblinfo[t].relname, PQerrorMessage(g_conn));
3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415
			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);
	}
}


3416 3417 3418 3419 3420 3421
/* 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).
 */

3422 3423
static void
becomeUser(FILE *fout, const char *username)
3424 3425 3426
{
	static const char *lastusername = "";

3427
	if (aclsSkip)
3428 3429 3430 3431 3432 3433 3434 3435 3436
		return;

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

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

	lastusername = username;
}