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

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

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

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

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

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

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

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

76 77
static void dumpComment(Archive *fout, const char *target, const char *oid,
						const char *classname, int subid,
78
						const char *((*deps)[]));
79
static void dumpSequence(Archive *fout, TableInfo tbinfo, const bool schemaOnly, const bool dataOnly);
B
Bruce Momjian 已提交
80 81
static void dumpACL(Archive *fout, TableInfo tbinfo);
static void dumpTriggers(Archive *fout, const char *tablename,
82
			 TableInfo *tblinfo, int numTables);
B
Bruce Momjian 已提交
83
static void dumpRules(Archive *fout, const char *tablename,
B
Bruce Momjian 已提交
84
		  TableInfo *tblinfo, int numTables);
85
static void formatStringLiteral(PQExpBuffer buf, const char *str, const formatLiteralOptions opts);
86
static void clearTableInfo(TableInfo *, int);
B
Bruce Momjian 已提交
87
static void dumpOneFunc(Archive *fout, FuncInfo *finfo, int i,
88
			TypeInfo *tinfo, int numTypes);
89 90
static Oid	findLastBuiltinOid_V71(const char *);
static Oid	findLastBuiltinOid_V70(void);
B
Bruce Momjian 已提交
91
static void setMaxOid(Archive *fout);
92

93
static void AddAcl(char *aclbuf, const char *keyword);
94
static char *GetPrivileges(Archive *AH, const char *s);
V
Vadim B. Mikheev 已提交
95

B
Bruce Momjian 已提交
96 97
static int	dumpBlobs(Archive *AH, char *, void *);
static int	dumpDatabase(Archive *AH);
98
static PQExpBuffer getPKconstraint(TableInfo *tblInfo, IndInfo *indInfo);
99
static const char *getAttrName(int attrnum, TableInfo *tblInfo);
100

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

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

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

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

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


B
Bruce Momjian 已提交
126 127 128 129
typedef struct _dumpContext
{
	TableInfo  *tblinfo;
	int			tblidx;
B
Bruce Momjian 已提交
130 131 132
	bool		oids;
} DumpContext;

133
static void
134
help(const char *progname)
135
{
136 137 138 139
	printf(gettext("%s dumps a database as a text file or to other formats.\n\n"), progname);
	puts(gettext("Usage:"));
	printf(gettext("  %s [options] dbname\n\n"), progname);
	puts(gettext("Options:"));
B
Hi,  
Bruce Momjian 已提交
140 141

#ifdef HAVE_GETOPT_LONG
142 143 144 145 146 147
	puts(gettext(
		"  -a, --data-only          dump only the data, not the schema\n"
		"  -b, --blobs              include BLOB data in dump\n"
		"  -c, --clean              clean (drop) schema prior to create\n"
		"  -C, --create             include commands to create database in dump\n"
		"  -d, --inserts            dump data as INSERT, rather than COPY, commands\n"
148
		"  -D, --column-inserts     dump data as INSERT commands with column names\n"
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
		"  -f, --file=FILENAME      output file name\n"
		"  -F, --format {c|t|p}     output file format (custom, tar, plain text)\n"
		"  -h, --host=HOSTNAME      database server host name\n"
		"  -i, --ignore-version     proceed even when server version mismatches\n"
		"                           pg_dump version\n"
		"  -n, --no-quotes          suppress most quotes around identifiers\n"
		"  -N, --quotes             enable most quotes around identifiers\n"
		"  -o, --oids               include oids in dump\n"
		"  -O, --no-owner           do not output \\connect commands in plain\n"
		"                           text format\n"
		"  -p, --port=PORT          database server port number\n"
		"  -R, --no-reconnect       disable ALL reconnections to the database in\n"
		"                           plain text format\n"
		"  -s, --schema-only        dump only the schema, no data\n"
		"  -S, --superuser=NAME     specify the superuser user name to use in\n"
		"                           plain text format\n"
		"  -t, --table=TABLE        dump this table only (* for all)\n"
		"  -U, --username=NAME      connect as specified database user\n"
		"  -v, --verbose            verbose mode\n"
		"  -W, --password           force password prompt (should happen automatically)\n"
169
		"  -x, --no-privileges      do not dump privileges (grant/revoke)\n"
170 171 172
		"  -X use-set-session-authorization, --use-set-session-authorization\n"
		"                           output SET SESSION AUTHORIZATION commands rather\n"
		"                           than \\connect commands\n"
173 174
		"  -Z, --compress {0-9}     compression level for compressed formats\n"
		));
B
Hi,  
Bruce Momjian 已提交
175
#else
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
	puts(gettext(
		"  -a                       dump only the data, not the schema\n"
		"  -b                       include BLOB data in dump\n"
		"  -c                       clean (drop) schema prior to create\n"
		"  -C                       include commands to create database in dump\n"
		"  -d                       dump data as INSERT, rather than COPY, commands\n"
		"  -D                       dump data as INSERT commands with column names\n"
		"  -f FILENAME              output file name\n"
		"  -F {c|t|p}               output file format (custom, tar, plain text)\n"
		"  -h HOSTNAME              database server host name\n"
		"  -i                       proceed even when server version mismatches\n"
		"                           pg_dump version\n"
		"  -n                       suppress most quotes around identifiers\n"
		"  -N                       enable most quotes around identifiers\n"
		"  -o                       include oids in dump\n"
		"  -O                       do not output \\connect commands in plain\n"
		"                           text format\n"
		"  -p PORT                  database server port number\n"
		"  -R                       disable ALL reconnections to the database in\n"
		"                           plain text format\n"
		"  -s                       dump only the schema, no data\n"
		"  -S NAME                  specify the superuser user name to use in\n"
		"                           plain text format\n"
		"  -t TABLE                 dump this table only (* for all)\n"
		"  -U NAME                  connect as specified database user\n"
		"  -v                       verbose mode\n"
		"  -W                       force password prompt (should happen automatically)\n"
		"  -x                       do not dump privileges (grant/revoke)\n"
204 205 206
		"  -X use-set-session-authorization\n"
		"                           output SET SESSION AUTHORIZATION commands rather\n"
		"                           than \\connect commands\n"
207 208
		"  -Z {0-9}                 compression level for compressed formats\n"
		));
B
Hi,  
Bruce Momjian 已提交
209
#endif
210 211 212
	puts(gettext("If no database name is not supplied, then the PGDATABASE environment\n"
				 "variable value is used.\n\n"
				 "Report bugs to <pgsql-bugs@postgresql.org>."));
213 214
}

215

216 217
void
exit_nicely(void)
218
{
219 220 221
	PQfinish(g_conn);
	if (g_verbose)
		write_msg(NULL, "*** aborted because of error\n");
222
	exit(1);
223 224 225
}


226 227
#define COPYBUFSIZ		8192

B
Bruce Momjian 已提交
228 229 230 231 232
/*
 *	Dump a table's contents for loading using the COPY command
 *	- this routine is called by the Archiver when it wants the table
 *	  to be dumped.
 */
233

B
Bruce Momjian 已提交
234 235
static int
dumpClasses_nodumpData(Archive *fout, char *oid, void *dctxv)
236
{
B
Bruce Momjian 已提交
237 238
	const DumpContext *dctx = (DumpContext *) dctxv;
	const char *classname = dctx->tblinfo[dctx->tblidx].relname;
239
	const bool	hasoids = dctx->tblinfo[dctx->tblidx].hasoids;
B
Bruce Momjian 已提交
240
	const bool	oids = dctx->oids;
241

242 243 244 245 246
	PGresult   *res;
	char		query[255];
	int			ret;
	bool		copydone;
	char		copybuf[COPYBUFSIZ];
247

B
Bruce Momjian 已提交
248
	if (g_verbose)
249
		write_msg(NULL, "dumping out the contents of table %s\n", classname);
250

251
	if (oids && hasoids)
252
	{
B
Bruce Momjian 已提交
253 254

		/*
255
		 * archprintf(fout, "COPY %s WITH OIDS FROM stdin;\n",
B
Bruce Momjian 已提交
256
		 * fmtId(classname, force_quotes));
257
		 *
B
Bruce Momjian 已提交
258
		 * - Not used as of V1.3 (needs to be in ArchiveEntry call)
259 260 261
		 *
		 */

262
		sprintf(query, "COPY %s WITH OIDS TO stdout;",
263
				fmtId(classname, force_quotes));
264 265 266
	}
	else
	{
B
Bruce Momjian 已提交
267 268 269 270

		/*
		 * archprintf(fout, "COPY %s FROM stdin;\n", fmtId(classname,
		 * force_quotes));
271 272 273 274 275
		 *
		 * - Not used as of V1.3 (needs to be in ArchiveEntry call)
		 *
		 */

276
		sprintf(query, "COPY %s TO stdout;", fmtId(classname, force_quotes));
277 278
	}
	res = PQexec(g_conn, query);
279 280
	if (!res ||
		PQresultStatus(res) == PGRES_FATAL_ERROR)
281
	{
282 283 284 285
		write_msg(NULL, "SQL command to dump the contents of table \"%s\" failed\n",
				  classname);
		write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
		write_msg(NULL, "The command was: %s\n", query);
286
		exit_nicely();
287 288 289 290 291
	}
	else
	{
		if (PQresultStatus(res) != PGRES_COPY_OUT)
		{
292 293 294 295 296
			write_msg(NULL, "SQL command to dump the contents of table \"%s\" executed abnormally.\n",
					  classname);
			write_msg(NULL, "The server returned status %d when %d was expected.\n", 
					  PQresultStatus(res), PGRES_COPY_OUT);
			write_msg(NULL, "The command was: %s\n", query);
297
			exit_nicely();
298 299 300 301
		}
		else
		{
			copydone = false;
302

303 304
			while (!copydone)
			{
305
				ret = PQgetline(g_conn, copybuf, COPYBUFSIZ);
306 307 308 309 310 311 312 313 314

				if (copybuf[0] == '\\' &&
					copybuf[1] == '.' &&
					copybuf[2] == '\0')
				{
					copydone = true;	/* don't print this... */
				}
				else
				{
B
Bruce Momjian 已提交
315
					archputs(copybuf, fout);
316 317
					switch (ret)
					{
318 319 320 321
						case EOF:
							copydone = true;
							/* FALLTHROUGH */
						case 0:
B
Bruce Momjian 已提交
322
							archputc('\n', fout);
323 324 325
							break;
						case 1:
							break;
326 327
					}
				}
328

B
Bruce Momjian 已提交
329
				/*
330 331
				 * THROTTLE:
				 *
B
Bruce Momjian 已提交
332 333 334 335 336
				 * There was considerable discussion in late July, 2000
				 * regarding slowing down pg_dump when backing up large
				 * tables. Users with both slow & fast (muti-processor)
				 * machines experienced performance degradation when doing
				 * a backup.
337
				 *
B
Bruce Momjian 已提交
338 339 340 341 342
				 * Initial attempts based on sleeping for a number of ms for
				 * each ms of work were deemed too complex, then a simple
				 * 'sleep in each loop' implementation was suggested. The
				 * latter failed because the loop was too tight. Finally,
				 * the following was implemented:
343
				 *
B
Bruce Momjian 已提交
344 345 346
				 * If throttle is non-zero, then See how long since the last
				 * sleep. Work out how long to sleep (based on ratio). If
				 * sleep is more than 100ms, then sleep reset timer EndIf
347 348
				 * EndIf
				 *
B
Bruce Momjian 已提交
349 350
				 * where the throttle value was the number of ms to sleep per
				 * ms of work. The calculation was done in each loop.
351
				 *
B
Bruce Momjian 已提交
352 353 354 355 356
				 * Most of the hard work is done in the backend, and this
				 * solution still did not work particularly well: on slow
				 * machines, the ratio was 50:1, and on medium paced
				 * machines, 1:1, and on fast multi-processor machines, it
				 * had little or no effect, for reasons that were unclear.
357 358 359
				 *
				 * Further discussion ensued, and the proposal was dropped.
				 *
B
Bruce Momjian 已提交
360 361 362 363 364 365
				 * For those people who want this feature, it can be
				 * implemented using gettimeofday in each loop,
				 * calculating the time since last sleep, multiplying that
				 * by the sleep ratio, then if the result is more than a
				 * preset 'minimum sleep time' (say 100ms), call the
				 * 'select' function to sleep for a subsecond period ie.
366
				 *
B
Bruce Momjian 已提交
367
				 * select(0, NULL, NULL, NULL, &tvi);
368
				 *
B
Bruce Momjian 已提交
369 370 371 372
				 * This will return after the interval specified in the
				 * structure tvi. Fianally, call gettimeofday again to
				 * save the 'last sleep time'.
				 */
373
			}
B
Bruce Momjian 已提交
374
			archprintf(fout, "\\.\n");
375
		}
376
		ret = PQendcopy(g_conn);
377 378
		if (ret != 0)
		{
379 380 381
			write_msg(NULL, "SQL command to dump the contents of table \"%s\" failed: PQendcopy() failed.\n", classname);
			write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
			write_msg(NULL, "The command was: %s\n", query);
B
Bruce Momjian 已提交
382
			PQclear(res);
383
			exit_nicely();
384 385
		}
	}
386

B
Bruce Momjian 已提交
387
	return 1;
388 389
}

B
Bruce Momjian 已提交
390
static int
B
Bruce Momjian 已提交
391
dumpClasses_dumpData(Archive *fout, char *oid, void *dctxv)
392
{
B
Bruce Momjian 已提交
393 394
	const DumpContext *dctx = (DumpContext *) dctxv;
	const char *classname = dctx->tblinfo[dctx->tblidx].relname;
B
Bruce Momjian 已提交
395

396 397
	PGresult   *res;
	PQExpBuffer q = createPQExpBuffer();
398 399
	int			tuple;
	int			field;
400

401 402
	if (fout->remoteVersion >= 70100)
	{
403
		appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR SELECT * FROM ONLY %s", fmtId(classname, force_quotes));
404
	} else {
405
		appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR SELECT * FROM %s", fmtId(classname, force_quotes));
406 407
	}

B
Hi, all  
Bruce Momjian 已提交
408
	res = PQexec(g_conn, q->data);
409
	if (!res ||
410
		PQresultStatus(res) != PGRES_COMMAND_OK)
411
	{
412 413 414
		write_msg(NULL, "dumpClasses(): SQL command failed\n");
		write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
		write_msg(NULL, "The command was: %s\n", q->data);
415
		exit_nicely();
416
	}
417 418 419 420 421 422 423
	
	do {
		PQclear(res);

		res = PQexec(g_conn, "FETCH 100 FROM _pg_dump_cursor");
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
424
		{
425 426 427 428
			write_msg(NULL, "dumpClasses(): SQL command failed\n");
			write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
			write_msg(NULL, "The command was: FETCH 100 FROM _pg_dump_cursor\n");
			exit_nicely();
429
		}
430 431

		for (tuple = 0; tuple < PQntuples(res); tuple++)
432
		{
433 434
			archprintf(fout, "INSERT INTO %s ", fmtId(classname, force_quotes));
			if (attrNames == true)
435
			{
436 437 438 439 440 441 442 443 444 445
				resetPQExpBuffer(q);
				appendPQExpBuffer(q, "(");
				for (field = 0; field < PQnfields(res); field++)
				{
					if (field > 0)
						appendPQExpBuffer(q, ",");
					appendPQExpBuffer(q, fmtId(PQfname(res, field), force_quotes));
				}
				appendPQExpBuffer(q, ") ");
				archprintf(fout, "%s", q->data);
446
			}
447 448
			archprintf(fout, "VALUES (");
			for (field = 0; field < PQnfields(res); field++)
449
			{
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
				if (field > 0)
					archprintf(fout, ",");
				if (PQgetisnull(res, tuple, field))
				{
					archprintf(fout, "NULL");
					continue;
				}
				switch (PQftype(res, field))
				{
					case INT2OID:
					case INT4OID:
					case OIDOID:	/* int types */
					case FLOAT4OID:
					case FLOAT8OID:/* float types */
						/* These types are printed without quotes */
						archprintf(fout, "%s",
								   PQgetvalue(res, tuple, field));
						break;
					case BITOID:
					case VARBITOID:
						archprintf(fout, "B'%s'",
								   PQgetvalue(res, tuple, field));
						break;
					default:
	
						/*
						 * All other types are printed as string literals,
						 * with appropriate escaping of special characters.
						 */
						resetPQExpBuffer(q);
						formatStringLiteral(q, PQgetvalue(res, tuple, field), CONV_ALL);
						archprintf(fout, "%s", q->data);
						break;
				}
484
			}
485
			archprintf(fout, ");\n");
486
		}
487 488 489 490 491 492 493 494 495 496 497 498

	} while( PQntuples(res) > 0 );
	PQclear(res);

	res = PQexec(g_conn, "CLOSE _pg_dump_cursor");
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		write_msg(NULL, "dumpClasses(): SQL command failed\n");
		write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
		write_msg(NULL, "The command was: CLOSE _pg_dump_cursor\n");
		exit_nicely();
499 500
	}
	PQclear(res);
501

502
	destroyPQExpBuffer(q);
B
Bruce Momjian 已提交
503
	return 1;
504 505
}

506 507 508 509 510 511 512 513
/*
 * Convert a string value to an SQL string literal,
 * with appropriate escaping of special characters.
 * Quote mark ' goes to '' per SQL standard, other
 * stuff goes to \ sequences.
 * The literal is appended to the given PQExpBuffer.
 */
static void
514
formatStringLiteral(PQExpBuffer buf, const char *str, const formatLiteralOptions opts)
515 516 517 518
{
	appendPQExpBufferChar(buf, '\'');
	while (*str)
	{
B
Bruce Momjian 已提交
519
		char		ch = *str++;
520 521 522

		if (ch == '\\' || ch == '\'')
		{
B
Bruce Momjian 已提交
523
			appendPQExpBufferChar(buf, ch);		/* double these */
524 525 526
			appendPQExpBufferChar(buf, ch);
		}
		else if ((unsigned char) ch < (unsigned char) ' ' &&
B
Bruce Momjian 已提交
527 528 529
				 (opts == CONV_ALL
				  || (ch != '\n' && ch != '\t')
				  ))
530
		{
B
Bruce Momjian 已提交
531 532 533 534 535

			/*
			 * generate octal escape for control chars other than
			 * whitespace
			 */
536 537 538 539 540 541 542 543 544 545 546
			appendPQExpBufferChar(buf, '\\');
			appendPQExpBufferChar(buf, ((ch >> 6) & 3) + '0');
			appendPQExpBufferChar(buf, ((ch >> 3) & 7) + '0');
			appendPQExpBufferChar(buf, (ch & 7) + '0');
		}
		else
			appendPQExpBufferChar(buf, ch);
	}
	appendPQExpBufferChar(buf, '\'');
}

547 548
/*
 * DumpClasses -
549
 *	  dump the contents of all the classes.
550 551
 */
static void
B
Bruce Momjian 已提交
552
dumpClasses(const TableInfo *tblinfo, const int numTables, Archive *fout,
B
Bruce Momjian 已提交
553
		 const char *onlytable, const bool oids, const bool force_quotes)
554
{
B
Bruce Momjian 已提交
555 556 557 558 559 560
	int			i;
	DataDumperPtr dumpFn;
	DumpContext *dumpCtx;
	char		copyBuf[512];
	char	   *copyStmt;

561
	if (g_verbose)
562 563 564 565 566 567
	{
		if (onlytable == NULL || (strlen(onlytable) == 0))
			write_msg(NULL, "preparing to dump the contents of all %d tables/sequences\n", numTables);
		else
			write_msg(NULL, "preparing to dump the contents of only one table/sequence\n");
	}
568

569 570
	for (i = 0; i < numTables; i++)
	{
571
		const char *classname = tblinfo[i].relname;
572 573

		/* Skip VIEW relations */
574
		if (tblinfo[i].viewdef != NULL)
575
			continue;
576 577

		if (tblinfo[i].sequence)/* already dumped */
V
Vadim B. Mikheev 已提交
578
			continue;
579

580
		if (!onlytable || (strcmp(classname, onlytable) == 0) || (strlen(onlytable) == 0))
581 582
		{
			if (g_verbose)
583
				write_msg(NULL, "preparing to dump the contents of table %s\n", classname);
584

585 586 587
#if 0
			becomeUser(fout, tblinfo[i].usename);
#endif
B
Bruce Momjian 已提交
588

B
Bruce Momjian 已提交
589 590
			dumpCtx = (DumpContext *) malloc(sizeof(DumpContext));
			dumpCtx->tblinfo = (TableInfo *) tblinfo;
B
Bruce Momjian 已提交
591 592
			dumpCtx->tblidx = i;
			dumpCtx->oids = oids;
593

594
			if (!dumpData)
595
			{
596
				/* Dump/restore using COPY */
B
Bruce Momjian 已提交
597
				dumpFn = dumpClasses_nodumpData;
598 599 600
				sprintf(copyBuf, "COPY %s %sFROM stdin;\n",
						fmtId(tblinfo[i].relname, force_quotes),
						(oids && tblinfo[i].hasoids) ? "WITH OIDS " : "");
601 602
				copyStmt = copyBuf;
			}
B
Bruce Momjian 已提交
603
			else
604
			{
605
				/* Restore using INSERT */
B
Bruce Momjian 已提交
606
				dumpFn = dumpClasses_dumpData;
607 608
				copyStmt = NULL;
			}
B
Bruce Momjian 已提交
609

P
Philip Warner 已提交
610
			ArchiveEntry(fout, tblinfo[i].oid, tblinfo[i].relname,
611 612
						 "TABLE DATA", NULL, "", "",
						 copyStmt, tblinfo[i].usename,
B
Bruce Momjian 已提交
613
						 dumpFn, dumpCtx);
614
		}
615
	}
616 617
}

618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641


static int
parse_version(const char* versionString)
{
	int			cnt;
	int			vmaj, vmin, vrev;

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

	if (cnt < 2)
	{
		write_msg(NULL, "unable to parse version string \"%s\"\n", versionString);
		exit(1);
	}

	if (cnt == 2)
		vrev = 0;

	return (100 * vmaj + vmin) * 100 + vrev;
}



642
int
643
main(int argc, char **argv)
644
{
B
Bruce Momjian 已提交
645 646
	int			c;
	const char *filename = NULL;
B
Bruce Momjian 已提交
647
	const char *format = "p";
B
Bruce Momjian 已提交
648 649 650
	const char *dbname = NULL;
	const char *pghost = NULL;
	const char *pgport = NULL;
651
	const char *username = NULL;
B
Bruce Momjian 已提交
652
	char	   *tablename = NULL;
653
	bool		oids = false;
B
Bruce Momjian 已提交
654 655
	TableInfo  *tblinfo;
	int			numTables;
656
	bool		force_password = false;
B
Bruce Momjian 已提交
657
	int			compressLevel = -1;
658
	bool		ignore_version = false;
659 660
	int			plainText = 0;
	int			outputClean = 0;
661
	int			outputCreate = 0;
662
	int			outputBlobs = 0;
663 664
	int			outputNoOwner = 0;
	int			outputNoReconnect = 0;
665
	static int	use_setsessauth = 0;
B
Bruce Momjian 已提交
666
	char	   *outputSuperuser = NULL;
667

B
Bruce Momjian 已提交
668
	RestoreOptions *ropt;
669

B
Hi,  
Bruce Momjian 已提交
670 671 672
#ifdef HAVE_GETOPT_LONG
	static struct option long_options[] = {
		{"data-only", no_argument, NULL, 'a'},
B
Bruce Momjian 已提交
673
		{"blobs", no_argument, NULL, 'b'},
B
Hi,  
Bruce Momjian 已提交
674
		{"clean", no_argument, NULL, 'c'},
675
		{"create", no_argument, NULL, 'C'},
B
Bruce Momjian 已提交
676 677
		{"file", required_argument, NULL, 'f'},
		{"format", required_argument, NULL, 'F'},
678
		{"inserts", no_argument, NULL, 'd'},
679
		{"attribute-inserts", no_argument, NULL, 'D'},
680
		{"column-inserts", no_argument, NULL, 'D'},
B
Hi,  
Bruce Momjian 已提交
681
		{"host", required_argument, NULL, 'h'},
682
		{"ignore-version", no_argument, NULL, 'i'},
683
		{"no-reconnect", no_argument, NULL, 'R'},
B
Hi,  
Bruce Momjian 已提交
684 685
		{"no-quotes", no_argument, NULL, 'n'},
		{"quotes", no_argument, NULL, 'N'},
686
		{"oids", no_argument, NULL, 'o'},
687
		{"no-owner", no_argument, NULL, 'O'},
B
Hi,  
Bruce Momjian 已提交
688 689
		{"port", required_argument, NULL, 'p'},
		{"schema-only", no_argument, NULL, 's'},
690
		{"superuser", required_argument, NULL, 'S'},
B
Hi,  
Bruce Momjian 已提交
691
		{"table", required_argument, NULL, 't'},
692 693
		{"password", no_argument, NULL, 'W'},
		{"username", required_argument, NULL, 'U'},
B
Hi,  
Bruce Momjian 已提交
694
		{"verbose", no_argument, NULL, 'v'},
695
		{"no-privileges", no_argument, NULL, 'x'},
B
Hi,  
Bruce Momjian 已提交
696
		{"no-acl", no_argument, NULL, 'x'},
B
Bruce Momjian 已提交
697
		{"compress", required_argument, NULL, 'Z'},
B
Hi,  
Bruce Momjian 已提交
698
		{"help", no_argument, NULL, '?'},
699 700 701 702 703
		{"version", no_argument, NULL, 'V'},

		/* the following options don't have an equivalent short option
           letter, but are available as '-X long-name' */
		{"use-set-session-authorization", no_argument, &use_setsessauth, 1}
704
	};
705 706
	int			optindex;

B
Hi,  
Bruce Momjian 已提交
707 708
#endif

709 710 711 712 713 714
#ifdef ENABLE_NLS
	setlocale(LC_ALL, "");
	bindtextdomain("pg_dump", LOCALEDIR);
	textdomain("pg_dump");
#endif

715
	g_verbose = false;
716
	force_quotes = true;
717 718 719 720 721

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

722
	dataOnly = schemaOnly = dumpData = attrNames = false;
723

724
	if (!strrchr(argv[0], '/'))
725 726
		progname = argv[0];
	else
727
		progname = strrchr(argv[0], '/') + 1;
728

729 730 731 732
	/* Set defaulty options based on progname */
	if (strcmp(progname, "pg_backup") == 0)
	{
		format = "c";
P
Philip Warner 已提交
733
		outputBlobs = true;
734
	}
735

736 737
	if (argc > 1)
	{
B
Bruce Momjian 已提交
738
		if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
739 740 741 742
		{
			help(progname);
			exit(0);
		}
B
Bruce Momjian 已提交
743
		if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
744
		{
745
			puts("pg_dump (PostgreSQL) " PG_VERSION);
746 747 748 749
			exit(0);
		}
	}

B
Hi,  
Bruce Momjian 已提交
750
#ifdef HAVE_GETOPT_LONG
751
	while ((c = getopt_long(argc, argv, "abcCdDf:F:h:inNoOp:RsS:t:uU:vWxX:zZ:V?", long_options, &optindex)) != -1)
B
Hi,  
Bruce Momjian 已提交
752
#else
753
	while ((c = getopt(argc, argv, "abcCdDf:F:h:inNoOp:RsS:t:uU:vWxX:zZ:V?-")) != -1)
B
Hi,  
Bruce Momjian 已提交
754
#endif
755

756 757 758
	{
		switch (c)
		{
759
			case 'a':			/* Dump data only */
760
				dataOnly = true;
761
				break;
762

763 764 765 766
			case 'b':			/* Dump blobs */
				outputBlobs = true;
				break;

B
Bruce Momjian 已提交
767
			case 'c':			/* clean (i.e., drop) schema prior to
B
Bruce Momjian 已提交
768
								 * create */
B
Bruce Momjian 已提交
769
				outputClean = 1;
B
Bruce Momjian 已提交
770 771
				break;

772 773 774 775 776
			case 'C':			/* Create DB */

				outputCreate = 1;
				break;

777
			case 'd':			/* dump data as proper insert strings */
778
				dumpData = true;
779
				break;
780

781 782
			case 'D':			/* dump data as proper insert strings with
								 * attr names */
783 784
				dumpData = true;
				attrNames = true;
785
				break;
786

787
			case 'f':
788 789
				filename = optarg;
				break;
790

B
Bruce Momjian 已提交
791 792 793
			case 'F':
				format = optarg;
				break;
794

B
Bruce Momjian 已提交
795
			case 'h':			/* server host */
796 797
				pghost = optarg;
				break;
798

799 800 801
			case 'i':			/* ignore database version mismatch */
				ignore_version = true;
				break;
802

B
Bruce Momjian 已提交
803 804
			case 'n':			/* Do not force double-quotes on
								 * identifiers */
805
				force_quotes = false;
806
				break;
807

808
			case 'N':			/* Force double-quotes on identifiers */
809
				force_quotes = true;
810
				break;
811

812
			case 'o':			/* Dump oids */
813
				oids = true;
814
				break;
815 816


817 818 819
			case 'O':			/* Don't reconnect to match owner */
				outputNoOwner = 1;
				break;
820

821 822 823
			case 'p':			/* server port */
				pgport = optarg;
				break;
824

825 826 827
			case 'R':			/* No reconnect */
				outputNoReconnect = 1;
				break;
828

829
			case 's':			/* dump schema only */
830
				schemaOnly = true;
831
				break;
832

B
Bruce Momjian 已提交
833 834
			case 'S':			/* Username for superuser in plain text
								 * output */
835 836
				outputSuperuser = strdup(optarg);
				break;
837

838
			case 't':			/* Dump data for this table only */
839
				{
840
					int			i;
841 842

					tablename = strdup(optarg);
B
Bruce Momjian 已提交
843 844 845 846 847

					/*
					 * quoted string? Then strip quotes and preserve
					 * case...
					 */
848 849 850
					if (tablename[0] == '"')
					{
						strcpy(tablename, &tablename[1]);
B
Bruce Momjian 已提交
851 852
						if (*(tablename + strlen(tablename) - 1) == '"')
							*(tablename + strlen(tablename) - 1) = '\0';
853 854 855 856 857
					}
					/* otherwise, convert table name to lowercase... */
					else
					{
						for (i = 0; tablename[i]; i++)
858 859
							if (isupper((unsigned char) tablename[i]))
								tablename[i] = tolower((unsigned char) tablename[i]);
860

B
Bruce Momjian 已提交
861 862 863 864 865
						/*
						 * '*' is a special case meaning ALL tables, but
						 * only if unquoted
						 */
						if (strcmp(tablename, "*") == 0)
866 867
							tablename[0] = '\0';

868
					}
869
				}
870
				break;
871

872
			case 'u':
873
				force_password = true;
874
				username = simple_prompt("User name: ", 100, true);
875 876 877 878
				break;

			case 'U':
				username = optarg;
879
				break;
880

881 882
			case 'v':			/* verbose */
				g_verbose = true;
883
				break;
884

885 886 887 888
			case 'W':
				force_password = true;
				break;

889 890
			case 'x':			/* skip ACL dump */
				aclsSkip = true;
891
				break;
892

893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
				/*
				 * Option letters were getting scarce, so I invented
				 * this new scheme: '-X feature' turns on some
				 * feature.  Compare to the -f option in GCC.  You
				 * should also add an equivalent GNU-style option
				 * --feature.  Features that require arguments should
				 * use '-X feature=foo'.
				 */
			case 'X':
				if (strcmp(optarg, "use-set-session-authorization")==0)
					use_setsessauth = 1;
				else
				{
					fprintf(stderr,
							gettext("%s: invalid -X option -- %s\n"),
							progname, optarg);
					fprintf(stderr, gettext("Try '%s --help' for more information.\n"), progname);
					exit(1);
				}
				break;
B
Bruce Momjian 已提交
913 914 915
			case 'Z':			/* Compression Level */
				compressLevel = atoi(optarg);
				break;
916

917 918
#ifndef HAVE_GETOPT_LONG
			case '-':
919 920 921 922
				fprintf(stderr,
						gettext("%s was compiled without support for long options.\n"
								"Use --help for help on invocation options.\n"),
						progname);
923 924
				exit(1);
				break;
925 926 927 928
#else
				/* This covers the long options equivalent to -X xxx. */
			case 0:
				break;
929
#endif
930
			default:
931
				fprintf(stderr, gettext("Try '%s --help' for more information.\n"), progname);
932
				exit(1);
933 934 935
		}
	}

B
Bruce Momjian 已提交
936 937
	if (optind < (argc - 1))
	{
P
Philip Warner 已提交
938
		fprintf(stderr,
939 940 941
				gettext("%s: too many command line options (first is '%s')\n"
						"Try '%s --help' for more information.\n"),
				progname, argv[optind + 1], progname);
P
Philip Warner 已提交
942 943 944
		exit(1);
	}

945 946 947 948 949 950 951
	/* Get the target database name */
	if (optind < argc)
		dbname = argv[optind];
	else
		dbname = getenv("PGDATABASE");
	if (!dbname)
	{
952
		write_msg(NULL, "no database name specified\n");
953 954 955
		exit(1);
	}

B
Bruce Momjian 已提交
956 957
	if (dataOnly && schemaOnly)
	{
958
		write_msg(NULL, "The options \"schema only\" (-s) and \"data only\" (-a) cannot be used together.\n");
B
Bruce Momjian 已提交
959 960 961
		exit(1);
	}

B
Bruce Momjian 已提交
962
	if (outputBlobs && tablename != NULL && strlen(tablename) > 0)
963
	{
964 965
		write_msg(NULL, "BLOB output is not supported for a single table.\n");
		write_msg(NULL, "Use all tables or a full dump instead.\n");
966 967 968
		exit(1);
	}

969 970
	if (dumpData == true && oids == true)
	{
971 972
		write_msg(NULL, "INSERT (-d, -D) and OID (-o) options cannot be used together.\n");
		write_msg(NULL, "(The INSERT command cannot set oids.)\n");
973
		exit(1);
974
	}
975

B
Bruce Momjian 已提交
976
	if (outputBlobs == true && (format[0] == 'p' || format[0] == 'P'))
P
Philip Warner 已提交
977
	{
978 979
		write_msg(NULL, "BLOB output is not supported for plain text dump files.\n");
		write_msg(NULL, "(Use a different output format.)\n");
P
Philip Warner 已提交
980 981 982
		exit(1);
	}

983
	/* open the output file */
B
Bruce Momjian 已提交
984 985
	switch (format[0])
	{
B
Bruce Momjian 已提交
986 987 988 989 990 991 992 993 994 995 996 997 998 999

		case 'c':
		case 'C':
			g_fout = CreateArchive(filename, archCustom, compressLevel);
			break;

		case 'f':
		case 'F':
			g_fout = CreateArchive(filename, archFiles, compressLevel);
			break;

		case 'p':
		case 'P':
			plainText = 1;
1000 1001 1002 1003 1004 1005
			g_fout = CreateArchive(filename, archNull, 0);
			break;

		case 't':
		case 'T':
			g_fout = CreateArchive(filename, archTar, compressLevel);
B
Bruce Momjian 已提交
1006 1007 1008
			break;

		default:
1009
			write_msg(NULL, "invalid output format '%s' specified\n", format);
B
Bruce Momjian 已提交
1010
			exit(1);
B
Bruce Momjian 已提交
1011 1012 1013 1014
	}

	if (g_fout == NULL)
	{
1015
		write_msg(NULL, "could not open output file %s for writing\n", filename);
B
Bruce Momjian 已提交
1016
		exit(1);
1017 1018
	}

1019 1020
	/* Let the archiver know how noisy to be */
	g_fout->verbose = g_verbose;
1021

B
Bruce Momjian 已提交
1022 1023
	/*
	 * Open the database using the Archiver, so it knows about it. Errors
1024
	 * mean death.
B
Bruce Momjian 已提交
1025
	 */
1026 1027
	g_fout->minRemoteVersion = 70000; /* we can handle back to 7.0 */
	g_fout->maxRemoteVersion = parse_version(PG_VERSION);
1028
	g_conn = ConnectDatabase(g_fout, dbname, pghost, pgport, username, force_password, ignore_version);
1029

1030 1031 1032 1033 1034 1035 1036 1037
	/*
	 * Start serializable transaction to dump consistent data
	 */
	{
		PGresult   *res;

		res = PQexec(g_conn, "begin");
		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
1038
			exit_horribly(g_fout, NULL, "BEGIN command failed: %s",
B
Bruce Momjian 已提交
1039
						  PQerrorMessage(g_conn));
1040

1041 1042 1043
		PQclear(res);
		res = PQexec(g_conn, "set transaction isolation level serializable");
		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
1044
			exit_horribly(g_fout, NULL, "could not set transaction isolation level to serializable: %s",
B
Bruce Momjian 已提交
1045
						  PQerrorMessage(g_conn));
1046

1047 1048 1049
		PQclear(res);
	}

1050 1051 1052 1053
	if (g_fout->remoteVersion >= 70100)
		g_last_builtin_oid = findLastBuiltinOid_V71(dbname);
	else
		g_last_builtin_oid = findLastBuiltinOid_V70();
1054

1055 1056 1057 1058
	/* Dump the database definition */
	if (!dataOnly)
		dumpDatabase(g_fout);

1059
	if (oids == true)
1060
		setMaxOid(g_fout);
B
Bruce Momjian 已提交
1061 1062

	if (g_verbose)
1063
		write_msg(NULL, "last built-in oid is %u\n", g_last_builtin_oid);
B
Bruce Momjian 已提交
1064
	tblinfo = dumpSchema(g_fout, &numTables, tablename, aclsSkip, oids, schemaOnly, dataOnly);
1065

1066
	if (!schemaOnly)
B
Bruce Momjian 已提交
1067
		dumpClasses(tblinfo, numTables, g_fout, tablename, oids, force_quotes);
1068 1069

	if (outputBlobs)
B
Bruce Momjian 已提交
1070
		ArchiveEntry(g_fout, "0", "BLOBS", "BLOBS", NULL, "", "", "", "", dumpBlobs, 0);
1071

1072 1073
	if (!dataOnly)				/* dump indexes and triggers at the end
								 * for performance */
V
Vadim B. Mikheev 已提交
1074 1075
	{
		dumpTriggers(g_fout, tablename, tblinfo, numTables);
1076
		dumpRules(g_fout, tablename, tblinfo, numTables);
V
Vadim B. Mikheev 已提交
1077
	}
1078

1079 1080
	/* Now sort the output nicely */
	SortTocByOID(g_fout);
1081
	MoveToStart(g_fout, "DATABASE");
1082 1083 1084
	MoveToEnd(g_fout, "TABLE DATA");
	MoveToEnd(g_fout, "BLOBS");
	MoveToEnd(g_fout, "INDEX");
1085
	MoveToEnd(g_fout, "CONSTRAINT");
1086 1087
	MoveToEnd(g_fout, "TRIGGER");
	MoveToEnd(g_fout, "RULE");
1088
	MoveToEnd(g_fout, "SEQUENCE SET");
1089 1090 1091 1092 1093 1094
	/*
	 * Moving all comments to end is annoying, but must do it for comments
	 * on stuff we just moved, and we don't seem to have quite enough
	 * dependency structure to get it really right...
	 */
	MoveToEnd(g_fout, "COMMENT");
1095

B
Bruce Momjian 已提交
1096
	if (plainText)
B
Bruce Momjian 已提交
1097 1098
	{
		ropt = NewRestoreOptions();
B
Bruce Momjian 已提交
1099
		ropt->filename = (char *) filename;
B
Bruce Momjian 已提交
1100 1101
		ropt->dropSchema = outputClean;
		ropt->aclsSkip = aclsSkip;
1102 1103 1104 1105
		ropt->superuser = outputSuperuser;
		ropt->create = outputCreate;
		ropt->noOwner = outputNoOwner;
		ropt->noReconnect = outputNoReconnect;
1106
		ropt->use_setsessauth = use_setsessauth;
1107 1108 1109 1110 1111

		if (outputSuperuser)
			ropt->superuser = outputSuperuser;
		else
			ropt->superuser = PQuser(g_conn);
B
Bruce Momjian 已提交
1112 1113

		if (compressLevel == -1)
B
Bruce Momjian 已提交
1114
			ropt->compression = 0;
B
Bruce Momjian 已提交
1115
		else
B
Bruce Momjian 已提交
1116
			ropt->compression = compressLevel;
B
Bruce Momjian 已提交
1117

1118 1119
		ropt->suppressDumpWarnings = true; /* We've already shown them */

B
Bruce Momjian 已提交
1120 1121 1122 1123
		RestoreArchive(g_fout, ropt);
	}

	CloseArchive(g_fout);
1124

1125 1126 1127
	clearTableInfo(tblinfo, numTables);
	PQfinish(g_conn);
	exit(0);
1128 1129
}

1130 1131 1132 1133 1134
/*
 * dumpDatabase:
 *	dump the database definition
 *
 */
B
Bruce Momjian 已提交
1135
static int
1136 1137
dumpDatabase(Archive *AH)
{
B
Bruce Momjian 已提交
1138 1139 1140 1141 1142 1143
	PQExpBuffer dbQry = createPQExpBuffer();
	PQExpBuffer delQry = createPQExpBuffer();
	PQExpBuffer creaQry = createPQExpBuffer();
	PGresult   *res;
	int			ntups;
	int			i_dba;
1144 1145

	if (g_verbose)
1146
		write_msg(NULL, "saving database definition\n");
1147 1148

	/* Get the dba */
1149
	appendPQExpBuffer(dbQry, "select (select usename from pg_user where datdba = usesysid) as dba from pg_database"
B
Bruce Momjian 已提交
1150
					  " where datname = ");
1151
	formatStringLiteral(dbQry, PQdb(g_conn), CONV_ALL);
1152 1153 1154 1155 1156

	res = PQexec(g_conn, dbQry->data);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1157 1158 1159
		write_msg(NULL, "SQL command failed\n");
		write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
		write_msg(NULL, "The command was: %s\n", dbQry->data);
1160
		exit_nicely();
1161 1162 1163 1164
	}

	ntups = PQntuples(res);

1165 1166 1167
	if (ntups <= 0)
	{
		write_msg(NULL, "missing pg_database entry for database \"%s\"\n", PQdb(g_conn));
1168
		exit_nicely();
1169 1170
	}

1171 1172
	if (ntups != 1)
	{
1173 1174
		write_msg(NULL, "query returned more than one (%d) pg_database entry for database \"%s\"\n",
				  ntups, PQdb(g_conn));
1175
		exit_nicely();
1176 1177 1178 1179 1180 1181
	}

	appendPQExpBuffer(creaQry, "Create Database \"%s\";\n", PQdb(g_conn));
	appendPQExpBuffer(delQry, "Drop Database \"%s\";\n", PQdb(g_conn));
	i_dba = PQfnumber(res, "dba");

B
Bruce Momjian 已提交
1182 1183 1184 1185
	ArchiveEntry(AH, "0" /* OID */ , PQdb(g_conn) /* Name */ , "DATABASE", NULL,
				 creaQry->data /* Create */ , delQry->data /* Del */ ,
				 "" /* Copy */ , PQgetvalue(res, 0, i_dba) /* Owner */ ,
				 NULL /* Dumper */ , NULL /* Dumper Arg */ );
1186 1187 1188

	PQclear(res);

1189 1190 1191 1192
	destroyPQExpBuffer(dbQry);
	destroyPQExpBuffer(delQry);
	destroyPQExpBuffer(creaQry);

1193 1194 1195 1196
	return 1;
}


1197 1198 1199 1200 1201 1202
/*
 * dumpBlobs:
 *	dump all blobs
 *
 */

B
Bruce Momjian 已提交
1203
#define loBufSize 16384
1204 1205
#define loFetchSize 1000

B
Bruce Momjian 已提交
1206 1207
static int
dumpBlobs(Archive *AH, char *junkOid, void *junkVal)
1208
{
B
Bruce Momjian 已提交
1209 1210 1211 1212 1213 1214 1215
	PQExpBuffer oidQry = createPQExpBuffer();
	PQExpBuffer oidFetchQry = createPQExpBuffer();
	PGresult   *res;
	int			i;
	int			loFd;
	char		buf[loBufSize];
	int			cnt;
1216
	Oid			blobOid;
1217 1218

	if (g_verbose)
1219
		write_msg(NULL, "saving BLOBs\n");
1220 1221

	/* Cursor to get all BLOB tables */
1222 1223 1224 1225 1226 1227
	if (AH->remoteVersion >= 70100)
	{
		appendPQExpBuffer(oidQry, "Declare blobOid Cursor for SELECT DISTINCT loid FROM pg_largeobject");
	} else {
		appendPQExpBuffer(oidQry, "Declare blobOid Cursor for SELECT oid from pg_class where relkind = 'l'");
	}
1228 1229 1230 1231

	res = PQexec(g_conn, oidQry->data);
	if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
	{
1232
		write_msg(NULL, "dumpBlobs(): cursor declaration failed: %s", PQerrorMessage(g_conn));
1233
		exit_nicely();
1234 1235 1236 1237 1238
	}

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

B
Bruce Momjian 已提交
1239 1240
	do
	{
1241 1242 1243 1244 1245 1246
		/* Do a fetch */
		PQclear(res);
		res = PQexec(g_conn, oidFetchQry->data);

		if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
		{
1247 1248
			write_msg(NULL, "dumpBlobs(): fetch from cursor failed: %s",
					  PQerrorMessage(g_conn));
1249
			exit_nicely();
1250 1251 1252 1253 1254
		}

		/* Process the tuples, if any */
		for (i = 0; i < PQntuples(res); i++)
		{
1255
			blobOid = atooid(PQgetvalue(res, i, 0));
1256 1257 1258 1259
			/* Open the BLOB */
			loFd = lo_open(g_conn, blobOid, INV_READ);
			if (loFd == -1)
			{
1260 1261
				write_msg(NULL, "dumpBlobs(): could not open large object: %s",
						  PQerrorMessage(g_conn));
1262
				exit_nicely();
1263 1264 1265 1266 1267
			}

			StartBlob(AH, blobOid);

			/* Now read it in chunks, sending data to archive */
B
Bruce Momjian 已提交
1268 1269
			do
			{
1270
				cnt = lo_read(g_conn, loFd, buf, loBufSize);
B
Bruce Momjian 已提交
1271 1272
				if (cnt < 0)
				{
1273 1274
					write_msg(NULL, "dumpBlobs(): error reading large object: %s",
							  PQerrorMessage(g_conn));
1275
					exit_nicely();
1276 1277
				}

B
Bruce Momjian 已提交
1278
				WriteData(AH, buf, cnt);
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288

			} while (cnt > 0);

			lo_close(g_conn, loFd);

			EndBlob(AH, blobOid);

		}
	} while (PQntuples(res) > 0);

1289 1290 1291
	destroyPQExpBuffer(oidQry);
	destroyPQExpBuffer(oidFetchQry);

1292 1293 1294
	return 1;
}

1295
/*
1296 1297
 * getTypes:
 *	  read all base types in the system catalogs and return them in the
1298 1299
 * TypeInfo* structure
 *
1300
 *	numTypes is set to the number of types read in
1301 1302
 *
 */
1303
TypeInfo   *
1304 1305
getTypes(int *numTypes)
{
B
Bruce Momjian 已提交
1306
	PGresult   *res;
1307 1308
	int			ntups;
	int			i;
1309
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
1310
	TypeInfo   *tinfo;
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324

	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;
1325 1326
	int			i_typalign;
	int			i_typstorage;
1327
	int			i_typbyval;
1328
	int			i_typisdefined;
1329
	int			i_usename;
1330
	int			i_typedefn;
1331 1332 1333 1334 1335 1336

	/* find all base types */

	/*
	 * we include even the built-in types because those may be used as
	 * array elements by user-defined types
1337
	 *
1338 1339 1340
	 * we filter out the built-in types when we dump out the types
	 */

1341 1342 1343 1344
	if (g_fout->remoteVersion < 70100)
	{
		appendPQExpBuffer(query, "SELECT pg_type.oid, typowner, typname, typlen, typprtlen, "
						"typinput, typoutput, typreceive, typsend, typelem, typdelim, "
1345
						"typdefault, typrelid, typalign, 'p'::char as typstorage, typbyval, typisdefined, "
1346 1347 1348 1349 1350 1351
						"(select usename from pg_user where typowner = usesysid) as usename, "
						"typname as typedefn "
						"from pg_type");
	} else {
		appendPQExpBuffer(query, "SELECT pg_type.oid, typowner, typname, typlen, typprtlen, "
						"typinput, typoutput, typreceive, typsend, typelem, typdelim, "
1352
						"typdefault, typrelid, typalign, typstorage, typbyval, typisdefined, "
1353 1354 1355 1356
						"(select usename from pg_user where typowner = usesysid) as usename, "
						"format_type(pg_type.oid, NULL) as typedefn "
						"from pg_type");
	}
1357

B
Hi, all  
Bruce Momjian 已提交
1358
	res = PQexec(g_conn, query->data);
1359 1360 1361
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1362
		write_msg(NULL, "query to obtain list of data types failed: %s", PQerrorMessage(g_conn));
1363
		exit_nicely();
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
	}

	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");
1383 1384
	i_typalign = PQfnumber(res, "typalign");
	i_typstorage = PQfnumber(res, "typstorage");
1385
	i_typbyval = PQfnumber(res, "typbyval");
1386
	i_typisdefined = PQfnumber(res, "typisdefined");
1387
	i_usename = PQfnumber(res, "usename");
1388
	i_typedefn = PQfnumber(res, "typedefn");
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404

	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));
1405 1406
		tinfo[i].typalign = strdup(PQgetvalue(res, i, i_typalign));
		tinfo[i].typstorage = strdup(PQgetvalue(res, i, i_typstorage));
1407
		tinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1408
		tinfo[i].typedefn = strdup(PQgetvalue(res, i, i_typedefn));
1409

1410
		if (strlen(tinfo[i].usename) == 0)
1411 1412
			write_msg(NULL, "WARNING: owner of data type %s appears to be invalid\n",
					  tinfo[i].typname);
1413

1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
		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;
1427 1428 1429 1430 1431

		if (strcmp(PQgetvalue(res, i, i_typisdefined), "f") == 0)
			tinfo[i].isDefined = 0;
		else
			tinfo[i].isDefined = 1;
1432 1433 1434 1435 1436 1437
	}

	*numTypes = ntups;

	PQclear(res);

1438 1439
	destroyPQExpBuffer(query);

1440
	return tinfo;
1441 1442 1443 1444
}

/*
 * getOperators:
1445
 *	  read all operators in the system catalogs and return them in the
1446 1447
 * OprInfo* structure
 *
1448 1449
 *	numOprs is set to the number of operators read in
 *
1450 1451
 *
 */
1452
OprInfo    *
1453 1454
getOperators(int *numOprs)
{
1455
	PGresult   *res;
1456 1457
	int			ntups;
	int			i;
1458
	PQExpBuffer query = createPQExpBuffer();
1459

B
Bruce Momjian 已提交
1460
	OprInfo    *oprinfo;
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475

	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;
1476 1477 1478 1479 1480 1481

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

B
Hi, all  
Bruce Momjian 已提交
1482
	appendPQExpBuffer(query, "SELECT pg_operator.oid, oprname, oprkind, oprcode, "
1483
			   "oprleft, oprright, oprcom, oprnegate, oprrest, oprjoin, "
B
Bruce Momjian 已提交
1484 1485 1486
					  "oprcanhash, oprlsortop, oprrsortop, "
	"(select usename from pg_user where oprowner = usesysid) as usename "
					  "from pg_operator");
1487

B
Hi, all  
Bruce Momjian 已提交
1488
	res = PQexec(g_conn, query->data);
1489 1490 1491
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1492
		write_msg(NULL, "query to obtain list of operators failed: %s", PQerrorMessage(g_conn));
1493
		exit_nicely();
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
	}

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

		if (strlen(oprinfo[i].usename) == 0)
1534 1535
			write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
					  oprinfo[i].oprname);
1536

1537 1538 1539 1540
	}

	PQclear(res);

1541 1542
	destroyPQExpBuffer(query);

1543
	return oprinfo;
1544 1545
}

1546
void
1547
clearTypeInfo(TypeInfo *tp, int numTypes)
1548
{
1549
	int			i;
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578

	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);
1579 1580 1581 1582
		if (tp[i].typalign)
			free(tp[i].typalign);
		if (tp[i].typstorage)
			free(tp[i].typstorage);
1583 1584
		if (tp[i].usename)
			free(tp[i].usename);
1585 1586
		if (tp[i].typedefn)
			free(tp[i].typedefn);
1587 1588
	}
	free(tp);
1589 1590 1591
}

void
1592
clearFuncInfo(FuncInfo *fun, int numFuncs)
1593
{
1594 1595
	int			i,
				a;
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606

	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);
1607
		for (a = 0; a < FUNC_MAX_ARGS; ++a)
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
			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);
1618 1619
}

1620
static void
1621
clearTableInfo(TableInfo *tblinfo, int numTables)
1622
{
1623 1624
	int			i,
				j;
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649

	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]);
		}
B
Bruce Momjian 已提交
1650

B
Bruce Momjian 已提交
1651 1652 1653
		if (tblinfo[i].triggers)
		{
			for (j = 0; j < tblinfo[i].ntrig; j++)
B
Bruce Momjian 已提交
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
			{
				if (tblinfo[i].triggers[j].tgsrc)
					free(tblinfo[i].triggers[j].tgsrc);
				if (tblinfo[i].triggers[j].oid)
					free(tblinfo[i].triggers[j].oid);
				if (tblinfo[i].triggers[j].tgname)
					free(tblinfo[i].triggers[j].tgname);
				if (tblinfo[i].triggers[j].tgdel)
					free(tblinfo[i].triggers[j].tgdel);
			}
			free(tblinfo[i].triggers);
		}

1667 1668
		if (tblinfo[i].atttypmod)
			free((int *) tblinfo[i].atttypmod);
1669 1670
		if (tblinfo[i].inhAttrs)
			free((int *) tblinfo[i].inhAttrs);
1671 1672 1673 1674
		if (tblinfo[i].inhAttrDef)
			free((int *) tblinfo[i].inhAttrDef);
		if (tblinfo[i].inhNotNull)
			free((int *) tblinfo[i].inhNotNull);
1675 1676
		if (tblinfo[i].attnames)
			free(tblinfo[i].attnames);
1677 1678
		if (tblinfo[i].atttypedefns)
			free(tblinfo[i].atttypedefns);
1679 1680 1681 1682
		if (tblinfo[i].typnames)
			free(tblinfo[i].typnames);
		if (tblinfo[i].notnull)
			free(tblinfo[i].notnull);
1683 1684
		if (tblinfo[i].primary_key_name)
			free(tblinfo[i].primary_key_name);
1685 1686
	}
	free(tblinfo);
1687 1688
}

1689
void
1690
clearInhInfo(InhInfo *inh, int numInherits)
1691
{
1692
	int			i;
1693 1694 1695 1696 1697

	if (!inh)
		return;
	for (i = 0; i < numInherits; ++i)
	{
1698 1699
		if (inh[i].inhrelid)
			free(inh[i].inhrelid);
1700 1701 1702 1703
		if (inh[i].inhparent)
			free(inh[i].inhparent);
	}
	free(inh);
1704 1705 1706
}

void
1707
clearOprInfo(OprInfo *opr, int numOprs)
1708
{
1709
	int			i;
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744

	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);
1745 1746 1747
}

void
1748
clearIndInfo(IndInfo *ind, int numIndexes)
1749
{
1750 1751
	int			i,
				a;
1752 1753 1754

	if (!ind)
		return;
1755
	for (i = 0; i < numIndexes; ++i)
1756
	{
1757 1758 1759 1760
		if (ind[i].indexreloid)
			free(ind[i].indexreloid);
		if (ind[i].indreloid)
			free(ind[i].indreloid);
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
		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);
1771 1772
		if (ind[i].indisprimary)
			free(ind[i].indisprimary);
1773 1774
		if (ind[i].indhaspred)
			free(ind[i].indhaspred);
1775 1776 1777 1778 1779 1780 1781 1782 1783
		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);
1784 1785 1786
}

void
B
Bruce Momjian 已提交
1787
clearAggInfo(AggInfo *agginfo, int numArgs)
1788
{
1789
	int			i;
1790 1791 1792 1793 1794 1795 1796 1797 1798

	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);
1799 1800
		if (agginfo[i].aggtransfn)
			free(agginfo[i].aggtransfn);
1801 1802
		if (agginfo[i].aggfinalfn)
			free(agginfo[i].aggfinalfn);
1803 1804
		if (agginfo[i].aggtranstype)
			free(agginfo[i].aggtranstype);
1805 1806
		if (agginfo[i].aggbasetype)
			free(agginfo[i].aggbasetype);
1807 1808
		if (agginfo[i].agginitval)
			free(agginfo[i].agginitval);
1809 1810 1811 1812
		if (agginfo[i].usename)
			free(agginfo[i].usename);
	}
	free(agginfo);
1813
}
1814 1815 1816

/*
 * getAggregates:
1817
 *	  read all the user-defined aggregates in the system catalogs and
1818 1819
 * return them in the AggInfo* structure
 *
1820 1821
 * numAggs is set to the number of aggregates read in
 *
1822 1823
 *
 */
1824
AggInfo    *
1825 1826
getAggregates(int *numAggs)
{
B
Bruce Momjian 已提交
1827
	PGresult   *res;
1828 1829
	int			ntups;
	int			i;
1830
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
1831
	AggInfo    *agginfo;
1832 1833 1834

	int			i_oid;
	int			i_aggname;
1835
	int			i_aggtransfn;
1836
	int			i_aggfinalfn;
1837
	int			i_aggtranstype;
1838
	int			i_aggbasetype;
1839
	int			i_agginitval;
1840
	int			i_usename;
1841
	int			i_convertok;
1842 1843 1844

	/* find all user-defined aggregates */

1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
	if (g_fout->remoteVersion < 70100)
	{
		appendPQExpBuffer(query, "SELECT pg_aggregate.oid, aggname, aggtransfn1 as aggtransfn, "
			"aggfinalfn, aggtranstype1 as aggtranstype, aggbasetype, "
			"agginitval1 as agginitval, "
			"(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) as convertok, "
			"(select usename from pg_user where aggowner = usesysid) as usename "
			"from pg_aggregate");
	} else {
		appendPQExpBuffer(query, "SELECT pg_aggregate.oid, aggname, aggtransfn, "
			"aggfinalfn, aggtranstype, aggbasetype, "
			"agginitval, "
			"'t'::boolean as convertok, "
			"(select usename from pg_user where aggowner = usesysid) as usename "
			"from pg_aggregate");
	}
1861

B
Hi, all  
Bruce Momjian 已提交
1862
	res = PQexec(g_conn, query->data);
1863 1864 1865
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1866
		write_msg(NULL, "query to obtain list of aggregate functions failed: %s",
1867
				  PQerrorMessage(g_conn));
1868
		exit_nicely();
1869 1870 1871 1872 1873 1874 1875 1876 1877
	}

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

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

	i_oid = PQfnumber(res, "oid");
	i_aggname = PQfnumber(res, "aggname");
1878
	i_aggtransfn = PQfnumber(res, "aggtransfn");
1879
	i_aggfinalfn = PQfnumber(res, "aggfinalfn");
1880
	i_aggtranstype = PQfnumber(res, "aggtranstype");
1881
	i_aggbasetype = PQfnumber(res, "aggbasetype");
1882
	i_agginitval = PQfnumber(res, "agginitval");
1883
	i_usename = PQfnumber(res, "usename");
1884
	i_convertok = PQfnumber(res, "convertok");
1885 1886 1887 1888 1889

	for (i = 0; i < ntups; i++)
	{
		agginfo[i].oid = strdup(PQgetvalue(res, i, i_oid));
		agginfo[i].aggname = strdup(PQgetvalue(res, i, i_aggname));
1890
		agginfo[i].aggtransfn = strdup(PQgetvalue(res, i, i_aggtransfn));
1891
		agginfo[i].aggfinalfn = strdup(PQgetvalue(res, i, i_aggfinalfn));
1892
		agginfo[i].aggtranstype = strdup(PQgetvalue(res, i, i_aggtranstype));
1893
		agginfo[i].aggbasetype = strdup(PQgetvalue(res, i, i_aggbasetype));
1894
		agginfo[i].agginitval = strdup(PQgetvalue(res, i, i_agginitval));
1895
		agginfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1896
		if (strlen(agginfo[i].usename) == 0)
1897 1898
			write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
					  agginfo[i].aggname);
1899

1900 1901
		agginfo[i].convertok = (PQgetvalue(res, i, i_convertok)[0] == 't');

1902 1903 1904 1905
	}

	PQclear(res);

1906 1907
	destroyPQExpBuffer(query);

1908
	return agginfo;
1909 1910 1911 1912
}

/*
 * getFuncs:
1913
 *	  read all the user-defined functions in the system catalogs and
1914 1915
 * return them in the FuncInfo* structure
 *
1916 1917
 * numFuncs is set to the number of functions read in
 *
1918 1919
 *
 */
1920
FuncInfo   *
1921 1922
getFuncs(int *numFuncs)
{
1923
	PGresult   *res;
1924 1925
	int			ntups;
	int			i;
1926 1927
	PQExpBuffer query = createPQExpBuffer();
	FuncInfo   *finfo;
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937

	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;
1938
	int			i_iscachable;
1939
	int			i_isstrict;
1940
	int			i_usename;
1941 1942 1943

	/* find all user-defined funcs */

1944 1945 1946 1947 1948 1949
	if (g_fout->remoteVersion < 70100)
	{
		appendPQExpBuffer(query,
		   "SELECT pg_proc.oid, proname, prolang, pronargs, prorettype, "
					  "proretset, proargtypes, prosrc, probin, "
				"(select usename from pg_user where proowner = usesysid) as usename, "
1950
				"proiscachable, 'f'::boolean as proisstrict "
1951 1952 1953 1954 1955
				"from pg_proc "
				"where pg_proc.oid > '%u'::oid",
					  g_last_builtin_oid);
	} else {
		appendPQExpBuffer(query,
1956
		   "SELECT pg_proc.oid, proname, prolang, pronargs, prorettype, "
1957
					  "proretset, proargtypes, prosrc, probin, "
1958 1959 1960 1961
				"(select usename from pg_user where proowner = usesysid) as usename, "
				"proiscachable, proisstrict "
				"from pg_proc "
				"where pg_proc.oid > '%u'::oid",
1962
					  g_last_builtin_oid);
1963
	}
1964

B
Hi, all  
Bruce Momjian 已提交
1965
	res = PQexec(g_conn, query->data);
1966 1967 1968
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1969 1970
		write_msg(NULL, "query to obtain list of functions failed: %s",
				  PQerrorMessage(g_conn));
1971
		exit_nicely();
1972 1973 1974 1975 1976 1977 1978 1979
	}

	ntups = PQntuples(res);

	*numFuncs = ntups;

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

1980 1981
	memset((char *) finfo, 0, ntups * sizeof(FuncInfo));

1982 1983 1984 1985 1986 1987 1988 1989 1990
	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");
1991
	i_iscachable = PQfnumber(res, "proiscachable");
1992
	i_isstrict = PQfnumber(res, "proisstrict");
1993 1994 1995 1996 1997 1998 1999
	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));

2000
		finfo[i].prosrc = strdup(PQgetvalue(res, i, i_prosrc));
2001 2002 2003 2004 2005
		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));
2006
		finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
2007
		finfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
B
Bruce Momjian 已提交
2008 2009
		finfo[i].iscachable = (strcmp(PQgetvalue(res, i, i_iscachable), "t") == 0);
		finfo[i].isstrict = (strcmp(PQgetvalue(res, i, i_isstrict), "t") == 0);
2010 2011

		if (strlen(finfo[i].usename) == 0)
2012 2013
			write_msg(NULL, "WARNING: owner of function \"%s\" appears to be invalid\n",
					  finfo[i].proname);
2014

2015 2016
		if (finfo[i].nargs < 0 || finfo[i].nargs > FUNC_MAX_ARGS)
		{
2017 2018
			write_msg(NULL, "failed sanity check: function %s has more than %d (namely %d) arguments\n",
					  finfo[i].proname, FUNC_MAX_ARGS, finfo[i].nargs);
2019
			exit_nicely();
2020 2021 2022 2023
		}
		parseNumericArray(PQgetvalue(res, i, i_proargtypes),
						  finfo[i].argtypes,
						  finfo[i].nargs);
2024 2025 2026 2027 2028
		finfo[i].dumped = 0;
	}

	PQclear(res);

2029
	destroyPQExpBuffer(query);
2030

2031
	return finfo;
2032 2033 2034 2035
}

/*
 * getTables
2036
 *	  read all the user-defined tables (no indexes, no catalogs)
2037 2038
 * in the system catalogs return them in the TableInfo* structure
 *
2039 2040
 * numTables is set to the number of tables read in
 *
2041 2042
 *
 */
2043
TableInfo  *
V
Vadim B. Mikheev 已提交
2044
getTables(int *numTables, FuncInfo *finfo, int numFuncs)
2045
{
2046
	PGresult   *res;
2047 2048
	int			ntups;
	int			i;
2049
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
2050
	PQExpBuffer delqry = createPQExpBuffer();
2051
	TableInfo  *tblinfo;
2052

B
Bruce Momjian 已提交
2053
	int			i_reloid;
2054 2055 2056 2057
	int			i_relname;
	int			i_relkind;
	int			i_relacl;
	int			i_usename;
V
Vadim B. Mikheev 已提交
2058 2059
	int			i_relchecks;
	int			i_reltriggers;
2060
	int			i_relhasindex;
2061
	int			i_relhasoids;
2062 2063 2064 2065 2066

	char		relkindview[2];

	relkindview[0] = RELKIND_VIEW;
	relkindview[1] = '\0';
2067 2068

	/*
2069
	 * find all the user-defined tables (no indexes and no catalogs),
2070 2071 2072
	 * ordering by oid is important so that we always process the parent
	 * tables before the child tables when traversing the tblinfo*
	 *
2073
	 * we ignore tables that are not type 'r' (ordinary relation) or 'S'
2074
	 * (sequence) or 'v' (view).
2075 2076
	 */

2077
	if (g_fout->remoteVersion >= 70200)
2078 2079
	{
		appendPQExpBuffer(query,
2080
					  "SELECT pg_class.oid, relname, relacl, relkind, "
2081
					  "(select usename from pg_user where relowner = usesysid) as usename, "
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
					  "relchecks, reltriggers, relhasindex, relhasoids "
					  "from pg_class "
					  "where relname !~ '^pg_' "
					  "and relkind in ('%c', '%c', '%c') "
					  "order by oid",
					  RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
	}
	else if (g_fout->remoteVersion >= 70100)
	{
		/* all tables have oids in 7.1 */
		appendPQExpBuffer(query,
					  "SELECT pg_class.oid, relname, relacl, relkind, "
					  "(select usename from pg_user where relowner = usesysid) as usename, "
					  "relchecks, reltriggers, relhasindex, 't'::bool as relhasoids "
2096 2097
					  "from pg_class "
					  "where relname !~ '^pg_' "
2098 2099
					  "and relkind in ('%c', '%c', '%c') "
					  "order by oid",
B
Bruce Momjian 已提交
2100
					  RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2101
	} else {
2102
		/*
2103 2104
		 * Before 7.1, view relkind was not set to 'v', so we must check
		 * if we have a view by looking for a rule in pg_rewrite.
2105 2106 2107 2108
		 */
		appendPQExpBuffer(query,
					  "SELECT c.oid, relname, relacl, "
					  "CASE WHEN relhasrules and relkind = 'r' "
2109 2110 2111 2112 2113
					  "  and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
					  "             r.ev_class = c.oid AND r.ev_type = '1') "
					  "THEN '%c'::\"char\" "
					  "ELSE relkind END AS relkind,"
					  "(select usename from pg_user where relowner = usesysid) as usename, "
2114
					  "relchecks, reltriggers, relhasindex, 't'::bool as relhasoids "
2115 2116 2117 2118
					  "from pg_class c "
					  "where relname !~ '^pg_' "
					  "and relkind in ('%c', '%c', '%c') "
					  "order by oid",
2119
					  RELKIND_VIEW,
2120 2121
					  RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
	}
2122

B
Hi, all  
Bruce Momjian 已提交
2123
	res = PQexec(g_conn, query->data);
2124 2125 2126
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
2127 2128
		write_msg(NULL, "query to obtain list of tables failed: %s",
				  PQerrorMessage(g_conn));
2129
		exit_nicely();
2130 2131 2132 2133 2134 2135 2136 2137
	}

	ntups = PQntuples(res);

	*numTables = ntups;

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

B
Bruce Momjian 已提交
2138
	i_reloid = PQfnumber(res, "oid");
2139 2140
	i_relname = PQfnumber(res, "relname");
	i_relacl = PQfnumber(res, "relacl");
2141
	i_relkind = PQfnumber(res, "relkind");
2142
	i_usename = PQfnumber(res, "usename");
V
Vadim B. Mikheev 已提交
2143 2144
	i_relchecks = PQfnumber(res, "relchecks");
	i_reltriggers = PQfnumber(res, "reltriggers");
B
Hi, all  
Bruce Momjian 已提交
2145
	i_relhasindex = PQfnumber(res, "relhasindex");
2146
	i_relhasoids = PQfnumber(res, "relhasoids");
2147 2148 2149

	for (i = 0; i < ntups; i++)
	{
B
Bruce Momjian 已提交
2150
		tblinfo[i].oid = strdup(PQgetvalue(res, i, i_reloid));
2151 2152 2153 2154
		tblinfo[i].relname = strdup(PQgetvalue(res, i, i_relname));
		tblinfo[i].relacl = strdup(PQgetvalue(res, i, i_relacl));
		tblinfo[i].sequence = (strcmp(PQgetvalue(res, i, i_relkind), "S") == 0);
		tblinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
V
Vadim B. Mikheev 已提交
2155 2156
		tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
		tblinfo[i].ntrig = atoi(PQgetvalue(res, i, i_reltriggers));
2157

2158
		if (strlen(tblinfo[i].usename) == 0)
2159 2160
			write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
					  tblinfo[i].relname);
2161

2162 2163 2164 2165 2166 2167
		/* Get view definition */
		if (strcmp(PQgetvalue(res, i, i_relkind), relkindview) == 0)
		{
			PGresult   *res2;

			resetPQExpBuffer(query);
2168 2169
			appendPQExpBuffer(query, "SELECT definition as viewdef, ");
			/* XXX 7.2 - replace with att from pg_views or some other generic source */
2170 2171 2172
			appendPQExpBuffer(query, "(select oid from pg_rewrite where "
										" rulename=('_RET' || viewname)::name) as view_oid"
										" from pg_views where viewname = ");
2173
			formatStringLiteral(query, tblinfo[i].relname, CONV_ALL);
2174 2175
			appendPQExpBuffer(query, ";");

2176 2177 2178
			res2 = PQexec(g_conn, query->data);
			if (!res2 || PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
2179 2180
				write_msg(NULL, "query to obtain definition of view \"%s\" failed: %s",
						  tblinfo[i].relname, PQerrorMessage(g_conn));
2181
				exit_nicely();
2182 2183
			}

B
Bruce Momjian 已提交
2184
			if (PQntuples(res2) != 1)
2185 2186
			{
				if (PQntuples(res2) < 1)
2187 2188
					write_msg(NULL, "query to obtain definition of view \"%s\" returned no data\n",
							  tblinfo[i].relname);
B
Bruce Momjian 已提交
2189
				else
2190
					write_msg(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
B
Bruce Momjian 已提交
2191
							tblinfo[i].relname);
2192
				exit_nicely();
2193 2194
			}

2195 2196
			if (PQgetisnull(res2, 0, 1))
			{
2197 2198
				write_msg(NULL, "query to obtain definition of view \"%s\" returned NULL oid\n",
						  tblinfo[i].relname);
2199
				exit_nicely();
2200 2201
			}

2202
			tblinfo[i].viewdef = strdup(PQgetvalue(res2, 0, 0));
2203
			tblinfo[i].viewoid = strdup(PQgetvalue(res2, 0, 1));
2204

B
Bruce Momjian 已提交
2205
			if (strlen(tblinfo[i].viewdef) == 0)
2206
			{
2207 2208
				write_msg(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
						  tblinfo[i].relname);
2209
				exit_nicely();
2210 2211 2212 2213 2214
			}
		}
		else
			tblinfo[i].viewdef = NULL;

2215
		/*
2216 2217
		 * Get non-inherited CHECK constraints, if any.
		 *
B
Bruce Momjian 已提交
2218 2219
		 * Exclude inherited CHECKs from CHECK constraints total. If a
		 * constraint matches by name and condition with a constraint
2220
		 * belonging to a parent class (OR conditions match and both
2221
		 * names start with '$', we assume it was inherited.
2222 2223
		 */
		if (tblinfo[i].ncheck > 0)
V
Vadim B. Mikheev 已提交
2224 2225
		{
			PGresult   *res2;
2226 2227
			int			i_rcname,
						i_rcsrc;
V
Vadim B. Mikheev 已提交
2228 2229
			int			ntups2;
			int			i2;
2230

V
Vadim B. Mikheev 已提交
2231
			if (g_verbose)
2232 2233
				write_msg(NULL, "finding CHECK constraints for table %s\n",
						  tblinfo[i].relname);
2234

B
Hi, all  
Bruce Momjian 已提交
2235 2236
			resetPQExpBuffer(query);
			appendPQExpBuffer(query, "SELECT rcname, rcsrc from pg_relcheck "
2237
							  " where rcrelid = '%s'::oid "
2238
							  "   and not exists "
2239 2240 2241 2242 2243 2244 2245 2246
							  "  (select * from pg_relcheck as c, pg_inherits as i "
							  "    where i.inhrelid = pg_relcheck.rcrelid "
							  "      and (c.rcname = pg_relcheck.rcname "
							  "          or (    c.rcname[0] = '$' "
							  "              and pg_relcheck.rcname[0] = '$')"
							  "          )"
							  "      and c.rcsrc = pg_relcheck.rcsrc "
							  "      and c.rcrelid = i.inhparent) "
2247
							  " order by rcname ",
2248
							  tblinfo[i].oid);
B
Hi, all  
Bruce Momjian 已提交
2249
			res2 = PQexec(g_conn, query->data);
V
Vadim B. Mikheev 已提交
2250
			if (!res2 ||
2251
				PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
2252
			{
2253
				write_msg(NULL, "query to obtain check constraints failed: %s", PQerrorMessage(g_conn));
2254
				exit_nicely();
V
Vadim B. Mikheev 已提交
2255 2256
			}
			ntups2 = PQntuples(res2);
2257
			if (ntups2 > tblinfo[i].ncheck)
V
Vadim B. Mikheev 已提交
2258
			{
2259 2260 2261
				write_msg(NULL, "expected %d check constraints on table \"%s\" but found %d\n",
						  tblinfo[i].ncheck, tblinfo[i].relname, ntups2);
				write_msg(NULL, "(The system catalogs might be corrupted.)\n");
2262
				exit_nicely();
V
Vadim B. Mikheev 已提交
2263
			}
2264 2265 2266 2267

			/* Set ncheck to the number of *non-inherited* CHECK constraints */
			tblinfo[i].ncheck = ntups2;

V
Vadim B. Mikheev 已提交
2268 2269
			i_rcname = PQfnumber(res2, "rcname");
			i_rcsrc = PQfnumber(res2, "rcsrc");
2270
			tblinfo[i].check_expr = (char **) malloc(ntups2 * sizeof(char *));
V
Vadim B. Mikheev 已提交
2271 2272
			for (i2 = 0; i2 < ntups2; i2++)
			{
B
Bruce Momjian 已提交
2273 2274
				const char *name = PQgetvalue(res2, i2, i_rcname);
				const char *expr = PQgetvalue(res2, i2, i_rcsrc);
2275

B
Hi, all  
Bruce Momjian 已提交
2276
				resetPQExpBuffer(query);
2277 2278
				if (name[0] != '$')
				{
2279 2280
					appendPQExpBuffer(query, "CONSTRAINT %s ",
									  fmtId(name, force_quotes));
B
Bruce Momjian 已提交
2281
				}
2282
				appendPQExpBuffer(query, "CHECK (%s)", expr);
B
Hi, all  
Bruce Momjian 已提交
2283
				tblinfo[i].check_expr[i2] = strdup(query->data);
V
Vadim B. Mikheev 已提交
2284 2285 2286 2287 2288
			}
			PQclear(res2);
		}
		else
			tblinfo[i].check_expr = NULL;
2289

2290 2291
		/* Get primary key */
		if (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0)
2292
		{
2293
			PGresult   *res2;
B
Bruce Momjian 已提交
2294

B
Hi, all  
Bruce Momjian 已提交
2295
			resetPQExpBuffer(query);
B
Bruce Momjian 已提交
2296
			appendPQExpBuffer(query,
2297
							  "SELECT indexrelid FROM pg_index i WHERE i.indisprimary AND i.indrelid = %s ",
2298
							  tblinfo[i].oid);
2299
			res2 = PQexec(g_conn, query->data);
B
Bruce Momjian 已提交
2300 2301
			if (!res2 || PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
2302 2303
				write_msg(NULL, "query to obtain primary key of table \"%s\" failed: %s",
						  tblinfo[i].relname, PQerrorMessage(g_conn));
2304
				exit_nicely();
B
Bruce Momjian 已提交
2305
			}
2306

B
Bruce Momjian 已提交
2307 2308
			if (PQntuples(res2) > 1)
			{
2309
				write_msg(NULL, "query to obtain primary key of table \"%s\" produced more than one result\n",
2310
						tblinfo[i].relname);
2311
				exit_nicely();
2312 2313
			}

B
Bruce Momjian 已提交
2314
			if (PQntuples(res2) == 1)
2315
				tblinfo[i].pkIndexOid = strdup(PQgetvalue(res2, 0, 0));
B
Bruce Momjian 已提交
2316
			else
2317 2318
				tblinfo[i].pkIndexOid = NULL;

2319
		}
2320
		else
2321
			tblinfo[i].pkIndexOid = NULL;
B
Bruce Momjian 已提交
2322

2323 2324 2325
		/* Has it got OIDs? */
		tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);

2326
		/* Get primary key name (if primary key exist) */
2327
		if (tblinfo[i].pkIndexOid != NULL)
2328 2329
		{
			PGresult   *res2;
B
Bruce Momjian 已提交
2330
			int			n;
2331 2332

			resetPQExpBuffer(query);
2333 2334 2335 2336
			appendPQExpBuffer(query,
							  "SELECT relname FROM pg_class "
							  "WHERE oid = %s",
							  tblinfo[i].pkIndexOid);
2337

2338 2339 2340
			res2 = PQexec(g_conn, query->data);
			if (!res2 || PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
2341 2342
				write_msg(NULL, "query to obtain name of primary key of table \"%s\" failed: %s",
						  tblinfo[i].relname, PQerrorMessage(g_conn));
2343
				exit_nicely();
2344 2345 2346 2347 2348
			}

			n = PQntuples(res2);
			if (n != 1)
			{
2349 2350
				write_msg(NULL, "query to obtain name of primary key of table \"%s\" did not return exactly one result\n",
						  tblinfo[i].relname);
2351
				exit_nicely();
2352 2353 2354 2355 2356 2357
			}

			tblinfo[i].primary_key_name =
				strdup(fmtId(PQgetvalue(res2, 0, 0), force_quotes));
			if (tblinfo[i].primary_key_name == NULL)
			{
2358
				write_msg(NULL, "out of memory\n");
2359
				exit_nicely();
2360 2361 2362 2363 2364
			}
		}
		else
			tblinfo[i].primary_key_name = NULL;

V
Vadim B. Mikheev 已提交
2365 2366 2367 2368
		/* Get Triggers */
		if (tblinfo[i].ntrig > 0)
		{
			PGresult   *res2;
B
Bruce,  
Bruce Momjian 已提交
2369
			int			i_tgoid,
2370
						i_tgname,
2371 2372 2373
						i_tgfoid,
						i_tgtype,
						i_tgnargs,
2374 2375 2376 2377
						i_tgargs,
						i_tgisconstraint,
						i_tgconstrname,
						i_tgdeferrable,
2378 2379
						i_tgconstrrelid,
						i_tgconstrrelname,
2380
						i_tginitdeferred;
V
Vadim B. Mikheev 已提交
2381 2382
			int			ntups2;
			int			i2;
2383

V
Vadim B. Mikheev 已提交
2384
			if (g_verbose)
2385
				write_msg(NULL, "finding triggers for table %s\n", tblinfo[i].relname);
2386

B
Hi, all  
Bruce Momjian 已提交
2387
			resetPQExpBuffer(query);
2388
			appendPQExpBuffer(query,
2389 2390 2391 2392 2393
								"SELECT tgname, tgfoid, tgtype, tgnargs, tgargs, "
								"tgisconstraint, tgconstrname, tgdeferrable, "
								"tgconstrrelid, tginitdeferred, oid, "
								"(select relname from pg_class where oid = tgconstrrelid) "
								"		as tgconstrrelname "
2394 2395 2396
							  "from pg_trigger "
							  "where tgrelid = '%s'::oid ",
							  tblinfo[i].oid);
B
Hi, all  
Bruce Momjian 已提交
2397
			res2 = PQexec(g_conn, query->data);
V
Vadim B. Mikheev 已提交
2398
			if (!res2 ||
2399
				PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
2400
			{
2401
				write_msg(NULL, "query to obtain list of triggers failed: %s", PQerrorMessage(g_conn));
2402
				exit_nicely();
V
Vadim B. Mikheev 已提交
2403 2404 2405 2406
			}
			ntups2 = PQntuples(res2);
			if (ntups2 != tblinfo[i].ntrig)
			{
2407 2408
				write_msg(NULL, "expected %d triggers on table \"%s\" but found %d\n",
						  tblinfo[i].ntrig, tblinfo[i].relname, ntups2);
2409
				exit_nicely();
V
Vadim B. Mikheev 已提交
2410 2411 2412 2413 2414 2415
			}
			i_tgname = PQfnumber(res2, "tgname");
			i_tgfoid = PQfnumber(res2, "tgfoid");
			i_tgtype = PQfnumber(res2, "tgtype");
			i_tgnargs = PQfnumber(res2, "tgnargs");
			i_tgargs = PQfnumber(res2, "tgargs");
B
Bruce,  
Bruce Momjian 已提交
2416
			i_tgoid = PQfnumber(res2, "oid");
2417 2418 2419
			i_tgisconstraint = PQfnumber(res2, "tgisconstraint");
			i_tgconstrname = PQfnumber(res2, "tgconstrname");
			i_tgdeferrable = PQfnumber(res2, "tgdeferrable");
2420 2421
			i_tgconstrrelid = PQfnumber(res2, "tgconstrrelid");
			i_tgconstrrelname = PQfnumber(res2, "tgconstrrelname");
2422 2423
			i_tginitdeferred = PQfnumber(res2, "tginitdeferred");

B
Bruce Momjian 已提交
2424
			tblinfo[i].triggers = (TrigInfo *) malloc(ntups2 * sizeof(TrigInfo));
B
Hi, all  
Bruce Momjian 已提交
2425 2426
			resetPQExpBuffer(query);
			for (i2 = 0; i2 < ntups2; i2++)
V
Vadim B. Mikheev 已提交
2427
			{
2428
				const char *tgfuncoid = PQgetvalue(res2, i2, i_tgfoid);
2429
				char	   *tgfunc = NULL;
2430 2431
				int2		tgtype = atoi(PQgetvalue(res2, i2, i_tgtype));
				int			tgnargs = atoi(PQgetvalue(res2, i2, i_tgnargs));
B
Bruce Momjian 已提交
2432
				const char *tgargs = PQgetvalue(res2, i2, i_tgargs);
2433 2434 2435
				int			tgisconstraint;
				int			tgdeferrable;
				int			tginitdeferred;
2436 2437
				char	   *tgconstrrelid;
				char	   *tgname;
B
Bruce Momjian 已提交
2438
				const char *p;
2439 2440
				int			findx;

2441 2442
				tgname = PQgetvalue(res2, i2, i_tgname);

2443
				if (strcmp(PQgetvalue(res2, i2, i_tgisconstraint), "f") == 0)
2444
					tgisconstraint = 0;
2445
				else
2446
					tgisconstraint = 1;
2447 2448

				if (strcmp(PQgetvalue(res2, i2, i_tgdeferrable), "f") == 0)
2449
					tgdeferrable = 0;
2450
				else
2451
					tgdeferrable = 1;
2452 2453

				if (strcmp(PQgetvalue(res2, i2, i_tginitdeferred), "f") == 0)
2454
					tginitdeferred = 0;
2455
				else
2456
					tginitdeferred = 1;
2457

V
Vadim B. Mikheev 已提交
2458 2459
				for (findx = 0; findx < numFuncs; findx++)
				{
2460
					if (strcmp(finfo[findx].oid, tgfuncoid) == 0 &&
2461
						finfo[findx].nargs == 0 &&
V
Vadim B. Mikheev 已提交
2462 2463 2464
						strcmp(finfo[findx].prorettype, "0") == 0)
						break;
				}
2465

V
Vadim B. Mikheev 已提交
2466 2467
				if (findx == numFuncs)
				{
2468
					PGresult   *r;
2469
					int			numFuncs;
2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486

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

					r = PQexec(g_conn, query->data);
					if (!r || PQresultStatus(r) != PGRES_TUPLES_OK)
					{
2487 2488
						write_msg(NULL, "query to obtain procedure name for trigger \"%s\" failed: %s",
								  tgname, PQerrorMessage(g_conn));
2489
						exit_nicely();
2490 2491 2492 2493
					}

					/* Sanity: Check we got only one tuple */
					numFuncs = PQntuples(r);
B
Bruce Momjian 已提交
2494 2495
					if (numFuncs != 1)
					{
2496 2497
						write_msg(NULL, "query to obtain procedure name for trigger \"%s\" did not return exactly one result\n",
								  tgname);
2498
						exit_nicely();
2499
					}
2500

2501
					tgfunc = strdup(PQgetvalue(r, 0, PQfnumber(r, "proname")));
2502
					PQclear(r);
2503
				}
2504
				else
2505
					tgfunc = strdup(finfo[findx].proname);
B
Bruce Momjian 已提交
2506

2507
				appendPQExpBuffer(delqry, "DROP TRIGGER %s ", fmtId(tgname, force_quotes));
B
Bruce Momjian 已提交
2508
				appendPQExpBuffer(delqry, "ON %s;\n",
B
Bruce Momjian 已提交
2509
								fmtId(tblinfo[i].relname, force_quotes));
2510

B
Hi, all  
Bruce Momjian 已提交
2511
				resetPQExpBuffer(query);
2512 2513 2514 2515 2516
				if (tgisconstraint)
				{
					appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
					appendPQExpBuffer(query, fmtId(PQgetvalue(res2, i2, i_tgconstrname), force_quotes));
				}
2517 2518
				else
				{
2519
					appendPQExpBuffer(query, "CREATE TRIGGER ");
2520
					appendPQExpBuffer(query, fmtId(tgname, force_quotes));
2521
				}
B
Bruce Momjian 已提交
2522
				appendPQExpBufferChar(query, ' ');
V
Vadim B. Mikheev 已提交
2523 2524 2525
				/* Trigger type */
				findx = 0;
				if (TRIGGER_FOR_BEFORE(tgtype))
B
Hi, all  
Bruce Momjian 已提交
2526
					appendPQExpBuffer(query, "BEFORE");
V
Vadim B. Mikheev 已提交
2527
				else
B
Hi, all  
Bruce Momjian 已提交
2528
					appendPQExpBuffer(query, "AFTER");
V
Vadim B. Mikheev 已提交
2529 2530
				if (TRIGGER_FOR_INSERT(tgtype))
				{
B
Hi, all  
Bruce Momjian 已提交
2531
					appendPQExpBuffer(query, " INSERT");
V
Vadim B. Mikheev 已提交
2532 2533 2534 2535 2536
					findx++;
				}
				if (TRIGGER_FOR_DELETE(tgtype))
				{
					if (findx > 0)
B
Hi, all  
Bruce Momjian 已提交
2537
						appendPQExpBuffer(query, " OR DELETE");
V
Vadim B. Mikheev 已提交
2538
					else
B
Hi, all  
Bruce Momjian 已提交
2539
						appendPQExpBuffer(query, " DELETE");
V
Vadim B. Mikheev 已提交
2540 2541 2542
					findx++;
				}
				if (TRIGGER_FOR_UPDATE(tgtype))
2543
				{
V
Vadim B. Mikheev 已提交
2544
					if (findx > 0)
B
Hi, all  
Bruce Momjian 已提交
2545
						appendPQExpBuffer(query, " OR UPDATE");
V
Vadim B. Mikheev 已提交
2546
					else
B
Hi, all  
Bruce Momjian 已提交
2547
						appendPQExpBuffer(query, " UPDATE");
2548
				}
2549 2550
				appendPQExpBuffer(query, " ON %s ", fmtId(tblinfo[i].relname, force_quotes));

2551
				if (tgisconstraint)
2552
				{
2553 2554 2555 2556 2557
					tgconstrrelid = PQgetvalue(res2, i2, i_tgconstrrelid);

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

						if (PQgetisnull(res2, i2, i_tgconstrrelname))
2558
						{
2559
							write_msg(NULL, "query produced NULL referenced table name for foreign key trigger \"%s\" on table \"%s\" (oid of table: %s)\n",
2560
									  tgname, tblinfo[i].relname, tgconstrrelid);
2561
							exit_nicely();
2562
						}
2563

2564
						appendPQExpBuffer(query, " FROM %s",
2565 2566
										fmtId(PQgetvalue(res2, i2, i_tgconstrrelname), force_quotes));
					}
2567
					if (!tgdeferrable)
2568 2569 2570 2571
						appendPQExpBuffer(query, " NOT");
					appendPQExpBuffer(query, " DEFERRABLE INITIALLY ");
					if (tginitdeferred)
						appendPQExpBuffer(query, "DEFERRED");
2572
					else
2573
						appendPQExpBuffer(query, "IMMEDIATE");
2574

2575 2576 2577
				}

				appendPQExpBuffer(query, " FOR EACH ROW");
2578 2579
				appendPQExpBuffer(query, " EXECUTE PROCEDURE %s (",
								  fmtId(tgfunc, force_quotes));
V
Vadim B. Mikheev 已提交
2580 2581
				for (findx = 0; findx < tgnargs; findx++)
				{
2582
					const char *s;
2583 2584

					for (p = tgargs;;)
V
Vadim B. Mikheev 已提交
2585
					{
2586
						p = strchr(p, '\\');
V
Vadim B. Mikheev 已提交
2587 2588
						if (p == NULL)
						{
2589 2590 2591 2592
							write_msg(NULL, "bad argument string (%s) for trigger \"%s\" on table \"%s\"\n",
									  PQgetvalue(res2, i2, i_tgargs),
									  tgname,
									  tblinfo[i].relname);
2593
							exit_nicely();
V
Vadim B. Mikheev 已提交
2594 2595 2596 2597 2598 2599 2600
						}
						p++;
						if (*p == '\\')
						{
							p++;
							continue;
						}
2601
						if (p[0] == '0' && p[1] == '0' && p[2] == '0')
V
Vadim B. Mikheev 已提交
2602 2603 2604
							break;
					}
					p--;
2605
					appendPQExpBufferChar(query, '\'');
B
Bruce Momjian 已提交
2606
					for (s = tgargs; s < p;)
V
Vadim B. Mikheev 已提交
2607 2608
					{
						if (*s == '\'')
2609 2610
							appendPQExpBufferChar(query, '\\');
						appendPQExpBufferChar(query, *s++);
V
Vadim B. Mikheev 已提交
2611
					}
B
Bruce Momjian 已提交
2612 2613
					appendPQExpBufferChar(query, '\'');
					appendPQExpBuffer(query, (findx < tgnargs - 1) ? ", " : "");
V
Vadim B. Mikheev 已提交
2614 2615
					tgargs = p + 4;
				}
B
Hi, all  
Bruce Momjian 已提交
2616
				appendPQExpBuffer(query, ");\n");
2617

B
Bruce Momjian 已提交
2618
				tblinfo[i].triggers[i2].tgsrc = strdup(query->data);
B
Bruce,  
Bruce Momjian 已提交
2619 2620

				/*** Initialize trcomments and troids ***/
2621

B
Bruce,  
Bruce Momjian 已提交
2622
				resetPQExpBuffer(query);
2623
				appendPQExpBuffer(query, "TRIGGER %s ",
2624
					fmtId(tgname, force_quotes));
B
Bruce,  
Bruce Momjian 已提交
2625
				appendPQExpBuffer(query, "ON %s",
2626
								fmtId(tblinfo[i].relname, force_quotes));
B
Bruce Momjian 已提交
2627 2628
				tblinfo[i].triggers[i2].tgcomment = strdup(query->data);
				tblinfo[i].triggers[i2].oid = strdup(PQgetvalue(res2, i2, i_tgoid));
2629
				tblinfo[i].triggers[i2].tgname = strdup(fmtId(tgname, false));
B
Bruce Momjian 已提交
2630
				tblinfo[i].triggers[i2].tgdel = strdup(delqry->data);
B
Bruce,  
Bruce Momjian 已提交
2631

2632 2633
				if (tgfunc)
					free(tgfunc);
V
Vadim B. Mikheev 已提交
2634 2635 2636 2637 2638
			}
			PQclear(res2);
		}
		else
			tblinfo[i].triggers = NULL;
2639

2640 2641 2642 2643
	}

	PQclear(res);

2644 2645
	destroyPQExpBuffer(query);
	destroyPQExpBuffer(delqry);
2646

2647
	return tblinfo;
2648 2649 2650 2651
}

/*
 * getInherits
2652
 *	  read all the inheritance information
2653 2654
 * from the system catalogs return them in the InhInfo* structure
 *
2655 2656
 * numInherits is set to the number of tables read in
 *
2657 2658
 *
 */
2659
InhInfo    *
2660 2661
getInherits(int *numInherits)
{
2662
	PGresult   *res;
2663 2664
	int			ntups;
	int			i;
2665 2666
	PQExpBuffer query = createPQExpBuffer();
	InhInfo    *inhinfo;
2667

2668
	int			i_inhrelid;
2669
	int			i_inhparent;
2670 2671 2672

	/* find all the inheritance information */

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

B
Hi, all  
Bruce Momjian 已提交
2675
	res = PQexec(g_conn, query->data);
2676 2677 2678
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
2679 2680
		write_msg(NULL, "query to obtain inheritance relationships failed: %s",
				  PQerrorMessage(g_conn));
2681
		exit_nicely();
2682 2683 2684 2685 2686 2687 2688 2689
	}

	ntups = PQntuples(res);

	*numInherits = ntups;

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

2690
	i_inhrelid = PQfnumber(res, "inhrelid");
2691 2692 2693 2694
	i_inhparent = PQfnumber(res, "inhparent");

	for (i = 0; i < ntups; i++)
	{
2695
		inhinfo[i].inhrelid = strdup(PQgetvalue(res, i, i_inhrelid));
2696 2697 2698 2699
		inhinfo[i].inhparent = strdup(PQgetvalue(res, i, i_inhparent));
	}

	PQclear(res);
2700 2701 2702

	destroyPQExpBuffer(query);

2703
	return inhinfo;
2704 2705 2706 2707
}

/*
 * getTableAttrs -
2708 2709
 *	  for each table in tblinfo, read its attributes types and names
 *
2710
 * this is implemented in a very inefficient way right now, looping
2711
 * through the tblinfo and doing a join per table to find the attrs and their
2712 2713
 * types
 *
2714
 *	modifies tblinfo
2715 2716
 */
void
2717
getTableAttrs(TableInfo *tblinfo, int numTables)
2718
{
2719 2720
	int			i,
				j;
2721
	PQExpBuffer q = createPQExpBuffer();
2722 2723
	int			i_attname;
	int			i_typname;
2724
	int			i_atttypmod;
2725
	int			i_attnotnull;
V
Vadim B. Mikheev 已提交
2726
	int			i_atthasdef;
2727
	int			i_atttypedefn;
2728
	PGresult   *res;
2729
	int			ntups;
2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743

	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)
2744 2745
			write_msg(NULL, "finding the columns and types for table %s\n",
					  tblinfo[i].relname);
2746

B
Hi, all  
Bruce Momjian 已提交
2747
		resetPQExpBuffer(q);
2748 2749 2750 2751

		if (g_fout->remoteVersion < 70100)
		{
			/* Fake the LOJ below */
2752
			appendPQExpBuffer(q,
2753
						"  SELECT a.attnum, a.attname, t.typname, a.atttypmod, "
2754 2755 2756 2757 2758
						"        a.attnotnull, a.atthasdef, NULL as atttypedefn "
						"    from pg_attribute a, pg_type t "
						"    where a.attrelid = '%s'::oid "
						"        and a.attnum > 0 "
						"        and a.atttypid = t.oid "
2759
						" UNION ALL SELECT a.attnum, a.attname, NULL as typname, a.atttypmod, "
2760 2761 2762 2763 2764 2765 2766 2767 2768
						"        a.attnotnull, a.atthasdef, NULL as atttypedefn "
						"    from pg_attribute a "
						"    where a.attrelid = '%s'::oid "
						"        and a.attnum > 0 "
						"        and Not Exists(Select * From pg_type t where a.atttypid = t.oid)"
						"    order by attnum",
						tblinfo[i].oid, tblinfo[i].oid);

		} else {
2769
			appendPQExpBuffer(q, "SELECT a.attnum, a.attname, t.typname, a.atttypmod, "
2770 2771 2772 2773 2774 2775 2776
								"a.attnotnull, a.atthasdef, format_type(a.atttypid, a.atttypmod) as atttypedefn "
								"from pg_attribute a LEFT OUTER JOIN pg_type t ON a.atttypid = t.oid "
								"where a.attrelid = '%s'::oid "
								"and a.attnum > 0 order by attnum",
								tblinfo[i].oid);
		}

B
Hi, all  
Bruce Momjian 已提交
2777
		res = PQexec(g_conn, q->data);
2778 2779 2780
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
2781
			write_msg(NULL, "query to get table columns failed: %s", PQerrorMessage(g_conn));
2782
			exit_nicely();
2783 2784 2785 2786 2787 2788
		}

		ntups = PQntuples(res);

		i_attname = PQfnumber(res, "attname");
		i_typname = PQfnumber(res, "typname");
2789
		i_atttypmod = PQfnumber(res, "atttypmod");
2790
		i_attnotnull = PQfnumber(res, "attnotnull");
V
Vadim B. Mikheev 已提交
2791
		i_atthasdef = PQfnumber(res, "atthasdef");
2792
		i_atttypedefn = PQfnumber(res, "atttypedefn");
2793 2794 2795

		tblinfo[i].numatts = ntups;
		tblinfo[i].attnames = (char **) malloc(ntups * sizeof(char *));
2796
		tblinfo[i].atttypedefns = (char **) malloc(ntups * sizeof(char *));
2797
		tblinfo[i].typnames = (char **) malloc(ntups * sizeof(char *));
2798
		tblinfo[i].atttypmod = (int *) malloc(ntups * sizeof(int));
2799
		tblinfo[i].inhAttrs = (int *) malloc(ntups * sizeof(int));
2800 2801
		tblinfo[i].inhAttrDef = (int *) malloc(ntups * sizeof(int));
		tblinfo[i].inhNotNull = (int *) malloc(ntups * sizeof(int));
2802
		tblinfo[i].notnull = (bool *) malloc(ntups * sizeof(bool));
V
Vadim B. Mikheev 已提交
2803
		tblinfo[i].adef_expr = (char **) malloc(ntups * sizeof(char *));
2804 2805 2806 2807
		tblinfo[i].parentRels = NULL;
		tblinfo[i].numParents = 0;
		for (j = 0; j < ntups; j++)
		{
2808 2809 2810
			/* Sanity check on LOJ */
			if (PQgetisnull(res, j, i_typname))
			{
2811 2812
				write_msg(NULL, "query produced NULL name for data type of column %d of table %s\n",
						  j+1, tblinfo[i].relname);
2813
				exit_nicely();
2814 2815
			}

2816
			tblinfo[i].attnames[j] = strdup(PQgetvalue(res, j, i_attname));
2817
			tblinfo[i].atttypedefns[j] = strdup(PQgetvalue(res, j, i_atttypedefn));
2818
			tblinfo[i].typnames[j] = strdup(PQgetvalue(res, j, i_typname));
2819
			tblinfo[i].atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
2820 2821
			tblinfo[i].inhAttrs[j] = 0; /* this flag is set in
										 * flagInhAttrs() */
2822 2823 2824
			tblinfo[i].inhAttrDef[j] = 0;
			tblinfo[i].inhNotNull[j] = 0;

2825
			tblinfo[i].notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't') ? true : false;
V
Vadim B. Mikheev 已提交
2826 2827 2828
			if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
			{
				PGresult   *res2;
2829
				int			numAttr;
2830

V
Vadim B. Mikheev 已提交
2831
				if (g_verbose)
2832 2833
					write_msg(NULL, "finding DEFAULT expression for column %s\n",
							  tblinfo[i].attnames[j]);
2834

B
Hi, all  
Bruce Momjian 已提交
2835 2836
				resetPQExpBuffer(q);
				appendPQExpBuffer(q, "SELECT adsrc from pg_attrdef "
2837 2838
							 "where adrelid = '%s'::oid and adnum = %d ",
								  tblinfo[i].oid, j + 1);
B
Hi, all  
Bruce Momjian 已提交
2839
				res2 = PQexec(g_conn, q->data);
V
Vadim B. Mikheev 已提交
2840
				if (!res2 ||
2841
					PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
2842
				{
2843 2844
					write_msg(NULL, "query to get column default value failed: %s",
							  PQerrorMessage(g_conn));
2845
					exit_nicely();
V
Vadim B. Mikheev 已提交
2846
				}
2847 2848 2849

				/* Sanity: Check we got only one tuple */
				numAttr = PQntuples(res2);
B
Bruce Momjian 已提交
2850 2851
				if (numAttr != 1)
				{
2852 2853
					write_msg(NULL, "query to get default value for column \"%s\" returned %d rows; expected 1\n",
							  tblinfo[i].attnames[j], numAttr);
2854
					exit_nicely();
2855 2856
				}

V
Vadim B. Mikheev 已提交
2857 2858 2859 2860 2861
				tblinfo[i].adef_expr[j] = strdup(PQgetvalue(res2, 0, PQfnumber(res2, "adsrc")));
				PQclear(res2);
			}
			else
				tblinfo[i].adef_expr[j] = NULL;
2862 2863 2864
		}
		PQclear(res);
	}
2865 2866

	destroyPQExpBuffer(q);
2867 2868 2869 2870
}


/*
2871 2872
 * getIndexes
 *	  read all the user-defined indexes information
2873 2874
 * from the system catalogs return them in the InhInfo* structure
 *
2875
 * numIndexes is set to the number of indexes read in
2876
 *
2877 2878
 *
 */
2879
IndInfo    *
2880
getIndexes(int *numIndexes)
2881
{
2882
	int			i;
2883
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
2884
	PGresult   *res;
2885
	int			ntups;
B
Bruce Momjian 已提交
2886
	IndInfo    *indinfo;
2887

2888 2889
	int			i_indexreloid;
	int			i_indreloid;
2890 2891 2892 2893 2894 2895 2896
	int			i_indexrelname;
	int			i_indrelname;
	int			i_indamname;
	int			i_indproc;
	int			i_indkey;
	int			i_indclass;
	int			i_indisunique;
2897
	int			i_indisprimary;
2898
	int			i_indhaspred;
2899 2900

	/*
2901
	 * find all the user-defined indexes.
2902
	 *
2903
	 * Notice we skip indexes on system classes
2904 2905
	 *
	 * this is a 4-way join !!
2906 2907
	 *
	 * XXXX: Use LOJ
2908 2909
	 */

B
Hi, all  
Bruce Momjian 已提交
2910
	appendPQExpBuffer(query,
2911 2912 2913
					  "SELECT i.indexrelid as indexreloid, "
					  "i.indrelid as indreloid, "
					  "t1.relname as indexrelname, t2.relname as indrelname, "
2914
					  "i.indproc :: oid AS indproc, i.indkey, i.indclass, "
2915 2916 2917 2918
					  "a.amname as indamname, i.indisunique, i.indisprimary, "
					  "length(i.indpred) > 0 as indhaspred "
					  "from pg_index i, pg_class t1, pg_class t2, pg_am a "
					  "WHERE t1.oid = i.indexrelid and t2.oid = i.indrelid "
2919
					  "and t1.relam = a.oid and i.indexrelid > '%u'::oid "
2920
					  "and t2.relname !~ '^pg_' ",
2921
					  g_last_builtin_oid);
2922

2923 2924 2925
	if (g_fout->remoteVersion < 70100)
		appendPQExpBuffer(query, " and t2.relkind != 'l'");

B
Hi, all  
Bruce Momjian 已提交
2926
	res = PQexec(g_conn, query->data);
2927 2928 2929
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
2930
		write_msg(NULL, "query to obtain list of indexes failed: %s", PQerrorMessage(g_conn));
2931
		exit_nicely();
2932 2933 2934 2935
	}

	ntups = PQntuples(res);

2936
	*numIndexes = ntups;
2937 2938 2939

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

2940 2941
	memset((char *) indinfo, 0, ntups * sizeof(IndInfo));

2942 2943
	i_indexreloid = PQfnumber(res, "indexreloid");
	i_indreloid = PQfnumber(res, "indreloid");
2944 2945 2946 2947 2948 2949 2950
	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");
2951
	i_indisprimary = PQfnumber(res, "indisprimary");
2952
	i_indhaspred = PQfnumber(res, "indhaspred");
2953 2954 2955

	for (i = 0; i < ntups; i++)
	{
2956 2957
		indinfo[i].indexreloid = strdup(PQgetvalue(res, i, i_indexreloid));
		indinfo[i].indreloid = strdup(PQgetvalue(res, i, i_indreloid));
2958 2959 2960 2961
		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));
2962 2963 2964 2965 2966 2967
		parseNumericArray(PQgetvalue(res, i, i_indkey),
						  indinfo[i].indkey,
						  INDEX_MAX_KEYS);
		parseNumericArray(PQgetvalue(res, i, i_indclass),
						  indinfo[i].indclass,
						  INDEX_MAX_KEYS);
2968
		indinfo[i].indisunique = strdup(PQgetvalue(res, i, i_indisunique));
2969
		indinfo[i].indisprimary = strdup(PQgetvalue(res, i, i_indisprimary));
2970
		indinfo[i].indhaspred = strdup(PQgetvalue(res, i, i_indhaspred));
2971 2972
	}
	PQclear(res);
2973 2974 2975

	destroyPQExpBuffer(query);

2976
	return indinfo;
2977 2978
}

B
Bruce,  
Bruce Momjian 已提交
2979
/*------------------------------------------------------------------
2980
 * dumpComment --
B
Bruce,  
Bruce Momjian 已提交
2981
 *
2982
 * This routine is used to dump any comments associated with the
B
Bruce,  
Bruce Momjian 已提交
2983
 * oid handed to this routine. The routine takes a constant character
2984 2985 2986 2987 2988 2989
 * string for the target part of the comment-creation command, plus
 * OID, class name, and subid which are the primary key for pg_description.
 * If a matching pg_description entry is found, it is dumped.
 * Additional dependencies can be passed for the comment, too --- this is
 * needed for VIEWs, whose comments are filed under the table OID but
 * which are dumped in order by their rule OID.
B
Bruce,  
Bruce Momjian 已提交
2990 2991 2992
 *------------------------------------------------------------------
*/

T
Tom Lane 已提交
2993
static void
2994
dumpComment(Archive *fout, const char *target, const char *oid,
2995
			const char *classname, int subid,
2996
			const char *((*deps)[]))
2997 2998
{
	PGresult   *res;
B
Bruce,  
Bruce Momjian 已提交
2999
	PQExpBuffer query;
3000
	int			i_description;
B
Bruce,  
Bruce Momjian 已提交
3001

3002 3003 3004 3005
	/* Comments are SCHEMA not data */
	if (dataOnly)
		return;

B
Bruce,  
Bruce Momjian 已提交
3006 3007 3008
	/*** Build query to find comment ***/

	query = createPQExpBuffer();
3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022

	if (fout->remoteVersion >= 70200)
	{
		appendPQExpBuffer(query, "SELECT description FROM pg_description "
						  "WHERE objoid = %s and classoid = "
						  "(SELECT oid FROM pg_class where relname = '%s') "
						  "and objsubid = %d",
						  oid, classname, subid);
	}
	else
	{
		/* Note: this will fail to find attribute comments in pre-7.2... */
		appendPQExpBuffer(query, "SELECT description FROM pg_description WHERE objoid = %s", oid);
	}
B
Bruce,  
Bruce Momjian 已提交
3023 3024 3025 3026

	/*** Execute query ***/

	res = PQexec(g_conn, query->data);
3027 3028
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
3029 3030
		write_msg(NULL, "query to get comment on oid %s failed: %s",
				   oid, PQerrorMessage(g_conn));
3031
		exit_nicely();
B
Bruce,  
Bruce Momjian 已提交
3032 3033 3034 3035
	}

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

3036
	if (PQntuples(res) == 1)
3037
	{
B
Bruce,  
Bruce Momjian 已提交
3038
		i_description = PQfnumber(res, "description");
B
Bruce Momjian 已提交
3039
		resetPQExpBuffer(query);
3040
		appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
3041 3042
		formatStringLiteral(query, PQgetvalue(res, 0, i_description),
							PASS_LFTAB);
3043
		appendPQExpBuffer(query, ";\n");
B
Bruce Momjian 已提交
3044

3045 3046
		ArchiveEntry(fout, oid, target, "COMMENT", deps,
					 query->data, "" /* Del */ ,
B
Bruce Momjian 已提交
3047
					 "" /* Copy */ , "" /* Owner */ , NULL, NULL);
B
Bruce,  
Bruce Momjian 已提交
3048 3049 3050 3051 3052
	}

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

	PQclear(res);
3053
	destroyPQExpBuffer(query);
B
Bruce,  
Bruce Momjian 已提交
3054 3055 3056
}

/*------------------------------------------------------------------
3057
 * dumpDBComment --
B
Bruce,  
Bruce Momjian 已提交
3058
 *
3059 3060
 * This routine is used to dump any comments associated with the
 * database to which we are currently connected. If the user chose
B
Bruce,  
Bruce Momjian 已提交
3061 3062 3063 3064 3065
 * to dump the schema of the database, then this is the first
 * statement issued.
 *------------------------------------------------------------------
*/

3066
void
B
Bruce Momjian 已提交
3067
dumpDBComment(Archive *fout)
3068 3069
{
	PGresult   *res;
B
Bruce,  
Bruce Momjian 已提交
3070
	PQExpBuffer query;
3071
	int			i_oid;
B
Bruce,  
Bruce Momjian 已提交
3072 3073 3074 3075

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

	query = createPQExpBuffer();
3076
	appendPQExpBuffer(query, "SELECT oid FROM pg_database WHERE datname = ");
3077
	formatStringLiteral(query, PQdb(g_conn), CONV_ALL);
B
Bruce,  
Bruce Momjian 已提交
3078 3079 3080 3081

	/*** Execute query ***/

	res = PQexec(g_conn, query->data);
3082 3083
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
3084 3085
		write_msg(NULL, "query to get database oid failed: %s",
				   PQerrorMessage(g_conn));
3086
		exit_nicely();
B
Bruce,  
Bruce Momjian 已提交
3087 3088 3089 3090
	}

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

3091 3092
	if (PQntuples(res) != 0)
	{
B
Bruce,  
Bruce Momjian 已提交
3093 3094 3095
		i_oid = PQfnumber(res, "oid");
		resetPQExpBuffer(query);
		appendPQExpBuffer(query, "DATABASE %s", fmtId(PQdb(g_conn), force_quotes));
3096 3097
		dumpComment(fout, query->data, PQgetvalue(res, 0, i_oid),
					"pg_database", 0, NULL);
B
Bruce,  
Bruce Momjian 已提交
3098 3099 3100 3101 3102
	}

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

	PQclear(res);
3103
	destroyPQExpBuffer(query);
B
Bruce,  
Bruce Momjian 已提交
3104 3105
}

3106 3107
/*
 * dumpTypes
3108
 *	  writes out to fout the queries to recreate all the user-defined types
3109 3110 3111
 *
 */
void
B
Bruce Momjian 已提交
3112
dumpTypes(Archive *fout, FuncInfo *finfo, int numFuncs,
3113
		  TypeInfo *tinfo, int numTypes)
3114
{
3115
	int			i;
3116
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3117
	PQExpBuffer delq = createPQExpBuffer();
3118
	int			funcInd;
3119
	const char *((*deps)[]);
3120
	int			depIdx;
3121 3122 3123 3124

	for (i = 0; i < numTypes; i++)
	{
		/* skip all the builtin types */
3125
		if (atooid(tinfo[i].oid) <= g_last_builtin_oid)
3126 3127 3128
			continue;

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

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

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

3141 3142 3143
		deps = malloc(sizeof(char*) * 10);
		depIdx = 0;

3144 3145 3146 3147 3148 3149
		/*
		 * 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)
3150 3151
		{
			(*deps)[depIdx++] = strdup(finfo[funcInd].oid);
3152
			dumpOneFunc(fout, finfo, funcInd, tinfo, numTypes);
3153
		}
3154 3155 3156

		funcInd = findFuncByName(finfo, numFuncs, tinfo[i].typoutput);
		if (funcInd != -1)
3157 3158
		{
			(*deps)[depIdx++] = strdup(finfo[funcInd].oid);
3159
			dumpOneFunc(fout, finfo, funcInd, tinfo, numTypes);
3160
		}
3161

3162
		resetPQExpBuffer(delq);
B
Bruce Momjian 已提交
3163
		appendPQExpBuffer(delq, "DROP TYPE %s;\n", fmtId(tinfo[i].typname, force_quotes));
3164

B
Hi, all  
Bruce Momjian 已提交
3165 3166
		resetPQExpBuffer(q);
		appendPQExpBuffer(q,
3167
						  "CREATE TYPE %s "
3168
						  "( internallength = %s, externallength = %s,",
3169 3170
						  fmtId(tinfo[i].typname, force_quotes),
						  tinfo[i].typlen,
3171 3172 3173 3174 3175 3176 3177 3178 3179 3180
						  tinfo[i].typprtlen);
		/* cannot combine these because fmtId uses static result area */
		appendPQExpBuffer(q, " input = %s,",
						  fmtId(tinfo[i].typinput, force_quotes));
		appendPQExpBuffer(q, " output = %s,",
						  fmtId(tinfo[i].typoutput, force_quotes));
		appendPQExpBuffer(q, " send = %s,",
						  fmtId(tinfo[i].typsend, force_quotes));
		appendPQExpBuffer(q, " receive = %s, default = ",
						  fmtId(tinfo[i].typreceive, force_quotes));
3181
		formatStringLiteral(q, tinfo[i].typdefault, CONV_ALL);
3182 3183 3184

		if (tinfo[i].isArray)
		{
3185
			char	   *elemType;
3186

3187
			elemType = findTypeByOid(tinfo, numTypes, tinfo[i].typelem, zeroAsOpaque);
3188 3189
			if (elemType == NULL)
			{
3190
				write_msg(NULL, "notice: array type %s - type for elements (oid %s) is not dumped\n",
3191
						  tinfo[i].typname, tinfo[i].typelem);
3192 3193 3194
				continue;
			}

3195
			appendPQExpBuffer(q, ", element = %s, delimiter = ", elemType);
3196
			formatStringLiteral(q, tinfo[i].typdelim, CONV_ALL);
3197 3198

			(*deps)[depIdx++] = strdup(tinfo[i].typelem);
3199
		}
3200

3201 3202 3203 3204 3205
		if (strcmp(tinfo[i].typalign, "c") == 0)
			appendPQExpBuffer(q, ", alignment = char");
		else if (strcmp(tinfo[i].typalign, "s") == 0)
			appendPQExpBuffer(q, ", alignment = int2");
		else if (strcmp(tinfo[i].typalign, "i") == 0)
3206 3207 3208 3209 3210 3211
			appendPQExpBuffer(q, ", alignment = int4");
		else if (strcmp(tinfo[i].typalign, "d") == 0)
			appendPQExpBuffer(q, ", alignment = double");

		if (strcmp(tinfo[i].typstorage, "p") == 0)
			appendPQExpBuffer(q, ", storage = plain");
3212
		else if (strcmp(tinfo[i].typstorage, "e") == 0)
3213
			appendPQExpBuffer(q, ", storage = external");
3214
		else if (strcmp(tinfo[i].typstorage, "x") == 0)
3215
			appendPQExpBuffer(q, ", storage = extended");
3216
		else if (strcmp(tinfo[i].typstorage, "m") == 0)
3217 3218
			appendPQExpBuffer(q, ", storage = main");

3219
		if (tinfo[i].passedbyvalue)
3220
			appendPQExpBuffer(q, ", passedbyvalue);\n");
3221
		else
B
Hi, all  
Bruce Momjian 已提交
3222
			appendPQExpBuffer(q, ");\n");
3223

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

		ArchiveEntry(fout, tinfo[i].oid, tinfo[i].typname, "TYPE", deps,
B
Bruce Momjian 已提交
3227
				  q->data, delq->data, "", tinfo[i].usename, NULL, NULL);
B
Bruce,  
Bruce Momjian 已提交
3228 3229 3230 3231

		/*** Dump Type Comments ***/

		resetPQExpBuffer(q);
B
Bruce Momjian 已提交
3232

B
Bruce,  
Bruce Momjian 已提交
3233
		appendPQExpBuffer(q, "TYPE %s", fmtId(tinfo[i].typname, force_quotes));
3234
		dumpComment(fout, q->data, tinfo[i].oid, "pg_type", 0, NULL);
3235
	}
3236 3237 3238

	destroyPQExpBuffer(q);
	destroyPQExpBuffer(delq);
3239 3240
}

3241 3242
/*
 * dumpProcLangs
B
Bruce Momjian 已提交
3243
 *		  writes out to fout the queries to recreate user-defined procedural languages
3244 3245 3246
 *
 */
void
B
Bruce Momjian 已提交
3247
dumpProcLangs(Archive *fout, FuncInfo *finfo, int numFuncs,
B
Bruce Momjian 已提交
3248
			  TypeInfo *tinfo, int numTypes)
3249
{
3250 3251
	PGresult   *res;
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
3252 3253
	PQExpBuffer defqry = createPQExpBuffer();
	PQExpBuffer delqry = createPQExpBuffer();
3254
	int			ntups;
B
Bruce Momjian 已提交
3255
	int			i_oid;
3256 3257 3258 3259
	int			i_lanname;
	int			i_lanpltrusted;
	int			i_lanplcallfoid;
	int			i_lancompiler;
3260
	Oid			lanoid;
3261 3262 3263
	char	   *lanname;
	char	   *lancompiler;
	const char *lanplcallfoid;
3264 3265 3266
	int			i,
				fidx;

B
Bruce Momjian 已提交
3267
	appendPQExpBuffer(query, "SELECT oid, * FROM pg_language "
3268 3269
					  "WHERE lanispl "
					  "ORDER BY oid");
B
Hi, all  
Bruce Momjian 已提交
3270
	res = PQexec(g_conn, query->data);
3271 3272 3273
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
3274 3275
		write_msg(NULL, "query to obtain list of procedural languages failed: %s",
				   PQerrorMessage(g_conn));
3276
		exit_nicely();
3277 3278 3279
	}
	ntups = PQntuples(res);

B
Bruce Momjian 已提交
3280 3281 3282 3283
	i_lanname = PQfnumber(res, "lanname");
	i_lanpltrusted = PQfnumber(res, "lanpltrusted");
	i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
	i_lancompiler = PQfnumber(res, "lancompiler");
B
Bruce Momjian 已提交
3284
	i_oid = PQfnumber(res, "oid");
3285

B
Bruce Momjian 已提交
3286 3287
	for (i = 0; i < ntups; i++)
	{
3288
		lanoid = atooid(PQgetvalue(res, i, i_oid));
3289 3290 3291
		if (lanoid <= g_last_builtin_oid)
			continue;

3292
		lanplcallfoid = PQgetvalue(res, i, i_lanplcallfoid);
3293 3294


3295 3296 3297 3298 3299 3300 3301
		for (fidx = 0; fidx < numFuncs; fidx++)
		{
			if (!strcmp(finfo[fidx].oid, lanplcallfoid))
				break;
		}
		if (fidx >= numFuncs)
		{
3302 3303
			write_msg(NULL, "handler procedure for procedural language %s not found\n",
					   PQgetvalue(res, i, i_lanname));
3304
			exit_nicely();
3305 3306 3307 3308
		}

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

3309 3310
		lanname = PQgetvalue(res, i, i_lanname);
		lancompiler = PQgetvalue(res, i, i_lancompiler);
3311

3312
		appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE ");
3313
		formatStringLiteral(delqry, lanname, CONV_ALL);
3314
		appendPQExpBuffer(delqry, ";\n");
3315

3316 3317 3318
		appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE ",
						  (PQgetvalue(res, i, i_lanpltrusted)[0] == 't') ?
						  "TRUSTED " : "");
3319
		formatStringLiteral(defqry, lanname, CONV_ALL);
3320 3321
		appendPQExpBuffer(defqry, " HANDLER %s LANCOMPILER ",
						  fmtId(finfo[fidx].proname, force_quotes));
3322
		formatStringLiteral(defqry, lancompiler, CONV_ALL);
3323
		appendPQExpBuffer(defqry, ";\n");
3324

B
Bruce Momjian 已提交
3325
		ArchiveEntry(fout, PQgetvalue(res, i, i_oid), lanname, "PROCEDURAL LANGUAGE",
B
Bruce Momjian 已提交
3326
				   NULL, defqry->data, delqry->data, "", "", NULL, NULL);
B
Bruce Momjian 已提交
3327

3328 3329
		resetPQExpBuffer(defqry);
		resetPQExpBuffer(delqry);
3330 3331 3332 3333
	}

	PQclear(res);

3334 3335 3336
	destroyPQExpBuffer(query);
	destroyPQExpBuffer(defqry);
	destroyPQExpBuffer(delqry);
3337 3338
}

3339 3340
/*
 * dumpFuncs
3341
 *	  writes out to fout the queries to recreate all the user-defined functions
3342 3343 3344
 *
 */
void
B
Bruce Momjian 已提交
3345
dumpFuncs(Archive *fout, FuncInfo *finfo, int numFuncs,
3346
		  TypeInfo *tinfo, int numTypes)
3347
{
3348
	int			i;
3349 3350 3351

	for (i = 0; i < numFuncs; i++)
		dumpOneFunc(fout, finfo, i, tinfo, numTypes);
3352 3353 3354 3355
}

/*
 * dumpOneFunc:
3356 3357
 *	  dump out only one function,  the index of which is given in the third
 *	argument
3358 3359 3360
 *
 */

3361
static void
B
Bruce Momjian 已提交
3362
dumpOneFunc(Archive *fout, FuncInfo *finfo, int i,
3363
			TypeInfo *tinfo, int numTypes)
3364
{
3365
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3366 3367
	PQExpBuffer fn = createPQExpBuffer();
	PQExpBuffer delqry = createPQExpBuffer();
B
Bruce,  
Bruce Momjian 已提交
3368
	PQExpBuffer fnlist = createPQExpBuffer();
3369
	PQExpBuffer asPart = createPQExpBuffer();
3370
	char		func_lang[NAMEDATALEN + 1];
3371 3372
	PGresult   *res;
	int			nlangs;
3373
	int			j;
3374 3375
	int			i_lanname;
	char		query[256];
3376

B
Bruce Momjian 已提交
3377 3378 3379 3380
	char	   *listSep;
	char	   *listSepComma = ",";
	char	   *listSepNone = "";
	char	   *rettypename;
3381

3382
	if (finfo[i].dumped)
3383 3384 3385
		goto done;

	finfo[i].dumped = 1;
3386

B
Bruce Momjian 已提交
3387
	/* becomeUser(fout, finfo[i].usename); */
3388

3389 3390 3391 3392 3393
	sprintf(query, "SELECT lanname FROM pg_language WHERE oid = %u",
			finfo[i].lang);
	res = PQexec(g_conn, query);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
B
Bruce Momjian 已提交
3394
	{
3395
		write_msg(NULL, "query to get name of procedural language failed: %s", PQerrorMessage(g_conn));
3396
		exit_nicely();
B
Bruce Momjian 已提交
3397
	}
3398 3399 3400
	nlangs = PQntuples(res);

	if (nlangs != 1)
B
Bruce Momjian 已提交
3401
	{
3402
		write_msg(NULL, "procedural language for function %s not found\n", finfo[i].proname);
3403
		exit_nicely();
B
Bruce Momjian 已提交
3404 3405
	}

3406
	i_lanname = PQfnumber(res, "lanname");
3407

3408
	/*
B
Bruce Momjian 已提交
3409 3410
	 * See backend/commands/define.c for details of how the 'AS' clause is
	 * used.
3411 3412 3413
	 */
	if (strcmp(finfo[i].probin, "-") != 0)
	{
3414
		appendPQExpBuffer(asPart, "AS ");
3415
		formatStringLiteral(asPart, finfo[i].probin, CONV_ALL);
3416
		if (strcmp(finfo[i].prosrc, "-") != 0)
3417 3418
		{
			appendPQExpBuffer(asPart, ", ");
3419
			formatStringLiteral(asPart, finfo[i].prosrc, PASS_LFTAB);
3420
		}
3421 3422 3423 3424
	}
	else
	{
		if (strcmp(finfo[i].prosrc, "-") != 0)
3425 3426
		{
			appendPQExpBuffer(asPart, "AS ");
3427
			formatStringLiteral(asPart, finfo[i].prosrc, PASS_LFTAB);
3428
		}
3429 3430
	}

3431
	strcpy(func_lang, PQgetvalue(res, 0, i_lanname));
B
Bruce Momjian 已提交
3432

3433
	PQclear(res);
B
Bruce Momjian 已提交
3434

B
Bruce Momjian 已提交
3435 3436
	resetPQExpBuffer(fn);
	appendPQExpBuffer(fn, "%s (", fmtId(finfo[i].proname, force_quotes));
3437 3438
	for (j = 0; j < finfo[i].nargs; j++)
	{
B
Bruce Momjian 已提交
3439
		char	   *typname;
3440

3441
		typname = findTypeByOid(tinfo, numTypes, finfo[i].argtypes[j], zeroAsOpaque);
3442 3443
		if (typname == NULL)
		{
3444 3445
			write_msg(NULL, "WARNING: function \"%s\" not dumped\n",
					  finfo[i].proname);
3446

3447
			write_msg(NULL, "reason: data type name of argument %d (oid %s) not found\n",
3448
					   j, finfo[i].argtypes[j]);
3449
			goto done;
3450 3451
		}

B
Bruce Momjian 已提交
3452 3453 3454
		appendPQExpBuffer(fn, "%s%s",
						  (j > 0) ? "," : "",
						  typname);
B
Bruce,  
Bruce Momjian 已提交
3455
		appendPQExpBuffer(fnlist, "%s%s",
B
Bruce Momjian 已提交
3456 3457
						  (j > 0) ? "," : "",
						  typname);
3458
	}
B
Bruce Momjian 已提交
3459 3460 3461
	appendPQExpBuffer(fn, ")");

	resetPQExpBuffer(delqry);
B
Bruce Momjian 已提交
3462
	appendPQExpBuffer(delqry, "DROP FUNCTION %s;\n", fn->data);
B
Bruce Momjian 已提交
3463

3464 3465 3466 3467
	rettypename = findTypeByOid(tinfo, numTypes, finfo[i].prorettype, zeroAsOpaque);

	if (rettypename == NULL)
	{
3468 3469
		write_msg(NULL, "WARNING: function \"%s\" not dumped\n",
				  finfo[i].proname);
3470

3471 3472
		write_msg(NULL, "reason: name of return data type (oid %s) not found\n",
				  finfo[i].prorettype);
3473
		goto done;
3474 3475
	}

B
Bruce Momjian 已提交
3476
	resetPQExpBuffer(q);
B
Bruce Momjian 已提交
3477
	appendPQExpBuffer(q, "CREATE FUNCTION %s ", fn->data);
3478 3479
	appendPQExpBuffer(q, "RETURNS %s%s %s LANGUAGE ",
					  (finfo[i].retset) ? "SETOF " : "",
3480
					  rettypename,
3481
					  asPart->data);
3482
	formatStringLiteral(q, func_lang, CONV_ALL);
3483

B
Bruce Momjian 已提交
3484
	if (finfo[i].iscachable || finfo[i].isstrict)		/* OR in new attrs here */
3485
	{
3486 3487 3488
		appendPQExpBuffer(q, " WITH (");
		listSep = listSepNone;

B
Bruce Momjian 已提交
3489 3490
		if (finfo[i].iscachable)
		{
3491 3492 3493 3494
			appendPQExpBuffer(q, "%s iscachable", listSep);
			listSep = listSepComma;
		}

B
Bruce Momjian 已提交
3495 3496
		if (finfo[i].isstrict)
		{
3497 3498 3499 3500
			appendPQExpBuffer(q, "%s isstrict", listSep);
			listSep = listSepComma;
		}
		appendPQExpBuffer(q, " )");
3501 3502 3503 3504
	}

	appendPQExpBuffer(q, ";\n");

B
Bruce Momjian 已提交
3505
	ArchiveEntry(fout, finfo[i].oid, fn->data, "FUNCTION", NULL, q->data, delqry->data,
B
Bruce Momjian 已提交
3506
				 "", finfo[i].usename, NULL, NULL);
3507

B
Bruce,  
Bruce Momjian 已提交
3508 3509 3510 3511 3512 3513
	/*** Dump Function Comments ***/

	resetPQExpBuffer(q);
	appendPQExpBuffer(q, "FUNCTION %s ",
					  fmtId(finfo[i].proname, force_quotes));
	appendPQExpBuffer(q, "( %s )", fnlist->data);
3514
	dumpComment(fout, q->data, finfo[i].oid, "pg_proc", 0, NULL);
3515 3516 3517 3518 3519 3520 3521

done:
	destroyPQExpBuffer(q);
	destroyPQExpBuffer(fn);
	destroyPQExpBuffer(delqry);
	destroyPQExpBuffer(fnlist);
	destroyPQExpBuffer(asPart);
3522 3523 3524 3525
}

/*
 * dumpOprs
3526
 *	  writes out to fout the queries to recreate all the user-defined operators
3527 3528
 *
 */
3529
void
B
Bruce Momjian 已提交
3530
dumpOprs(Archive *fout, OprInfo *oprinfo, int numOperators,
3531
		 TypeInfo *tinfo, int numTypes)
3532
{
B
Bruce Momjian 已提交
3533
	int			i;
3534
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3535
	PQExpBuffer delq = createPQExpBuffer();
3536 3537 3538 3539 3540 3541 3542 3543
	PQExpBuffer leftarg = createPQExpBuffer();
	PQExpBuffer rightarg = createPQExpBuffer();
	PQExpBuffer commutator = createPQExpBuffer();
	PQExpBuffer negator = createPQExpBuffer();
	PQExpBuffer restrictor = createPQExpBuffer();
	PQExpBuffer join = createPQExpBuffer();
	PQExpBuffer sort1 = createPQExpBuffer();
	PQExpBuffer sort2 = createPQExpBuffer();
3544 3545 3546

	for (i = 0; i < numOperators; i++)
	{
B
Bruce Momjian 已提交
3547
		char	   *name;
3548

B
Hi, all  
Bruce Momjian 已提交
3549 3550 3551 3552 3553 3554 3555 3556 3557
		resetPQExpBuffer(leftarg);
		resetPQExpBuffer(rightarg);
		resetPQExpBuffer(commutator);
		resetPQExpBuffer(negator);
		resetPQExpBuffer(restrictor);
		resetPQExpBuffer(join);
		resetPQExpBuffer(sort1);
		resetPQExpBuffer(sort2);

3558
		/* skip all the builtin oids */
3559
		if (atooid(oprinfo[i].oid) <= g_last_builtin_oid)
3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575
			continue;

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

		/*
		 * right unary means there's a left arg and left unary means
		 * there's a right arg
		 */
		if (strcmp(oprinfo[i].oprkind, "r") == 0 ||
			strcmp(oprinfo[i].oprkind, "b") == 0)
		{
B
Bruce Momjian 已提交
3576 3577
			name = findTypeByOid(tinfo, numTypes,
								 oprinfo[i].oprleft, zeroAsOpaque);
3578 3579
			if (name == NULL)
			{
3580 3581 3582 3583
				write_msg(NULL, "WARNING: operator \"%s\" (oid %s) not dumped\n",
						  oprinfo[i].oprname, oprinfo[i].oid);
				write_msg(NULL, "reason: oprleft (oid %s) not found\n",
						  oprinfo[i].oprleft);
3584 3585
				continue;
			}
B
Bruce Momjian 已提交
3586
			appendPQExpBuffer(leftarg, ",\n\tLEFTARG = %s ", name);
3587
		}
3588

3589 3590 3591
		if (strcmp(oprinfo[i].oprkind, "l") == 0 ||
			strcmp(oprinfo[i].oprkind, "b") == 0)
		{
B
Bruce Momjian 已提交
3592 3593
			name = findTypeByOid(tinfo, numTypes,
								 oprinfo[i].oprright, zeroAsOpaque);
3594 3595
			if (name == NULL)
			{
3596 3597 3598 3599
				write_msg(NULL, "WARNING: operator \"%s\" (oid %s) not dumped\n",
						  oprinfo[i].oprname, oprinfo[i].oid);
				write_msg(NULL, "reason: oprright (oid %s) not found\n",
						  oprinfo[i].oprright);
3600 3601 3602
				continue;
			}
			appendPQExpBuffer(rightarg, ",\n\tRIGHTARG = %s ", name);
3603
		}
3604

B
Hi, all  
Bruce Momjian 已提交
3605
		if (!(strcmp(oprinfo[i].oprcom, "0") == 0))
3606 3607 3608 3609
		{
			name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprcom);
			if (name == NULL)
			{
3610 3611 3612 3613
				write_msg(NULL, "WARNING: operator \"%s\" (oid %s) not dumped\n",
						  oprinfo[i].oprname, oprinfo[i].oid);
				write_msg(NULL, "reason: oprcom (oid %s) not found\n",
						  oprinfo[i].oprcom);
3614 3615 3616 3617
				continue;
			}
			appendPQExpBuffer(commutator, ",\n\tCOMMUTATOR = %s ", name);
		}
3618

B
Hi, all  
Bruce Momjian 已提交
3619
		if (!(strcmp(oprinfo[i].oprnegate, "0") == 0))
3620 3621 3622 3623
		{
			name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprnegate);
			if (name == NULL)
			{
3624 3625 3626 3627
				write_msg(NULL, "WARNING: operator \"%s\" (oid %s) not dumped\n",
						  oprinfo[i].oprname, oprinfo[i].oid);
				write_msg(NULL, "reason: oprnegate (oid %s) not found\n",
						  oprinfo[i].oprnegate);
3628 3629 3630 3631
				continue;
			}
			appendPQExpBuffer(negator, ",\n\tNEGATOR = %s ", name);
		}
3632

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

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

B
Hi, all  
Bruce Momjian 已提交
3639
		if (!(strcmp(oprinfo[i].oprlsortop, "0") == 0))
3640
		{
B
Bruce Momjian 已提交
3641
			name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprlsortop);
3642 3643
			if (name == NULL)
			{
3644 3645 3646 3647
				write_msg(NULL, "WARNING: operator \"%s\" (oid %s) not dumped\n",
						  oprinfo[i].oprname, oprinfo[i].oid);
				write_msg(NULL, "reason: oprlsortop (oid %s) not found\n",
						  oprinfo[i].oprlsortop);
3648 3649 3650 3651
				continue;
			}
			appendPQExpBuffer(sort1, ",\n\tSORT1 = %s ", name);
		}
3652

B
Hi, all  
Bruce Momjian 已提交
3653
		if (!(strcmp(oprinfo[i].oprrsortop, "0") == 0))
3654
		{
B
Bruce Momjian 已提交
3655
			name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprrsortop);
3656 3657
			if (name == NULL)
			{
3658 3659 3660 3661
				write_msg(NULL, "WARNING: operator \"%s\" (oid %s) not dumped\n",
						  oprinfo[i].oprname, oprinfo[i].oid);
				write_msg(NULL, "reason: oprrsortop (oid %s) not found\n",
						  oprinfo[i].oprrsortop);
3662 3663 3664 3665
				continue;
			}
			appendPQExpBuffer(sort2, ",\n\tSORT2 = %s ", name);
		}
3666

B
Bruce Momjian 已提交
3667 3668
		resetPQExpBuffer(delq);
		appendPQExpBuffer(delq, "DROP OPERATOR %s (%s", oprinfo[i].oprname,
B
Bruce Momjian 已提交
3669
		findTypeByOid(tinfo, numTypes, oprinfo[i].oprleft, zeroAsOpaque));
B
Bruce Momjian 已提交
3670
		appendPQExpBuffer(delq, ", %s);\n",
B
Bruce Momjian 已提交
3671
						  findTypeByOid(tinfo, numTypes, oprinfo[i].oprright, zeroAsOpaque));
3672

B
Hi, all  
Bruce Momjian 已提交
3673 3674
		resetPQExpBuffer(q);
		appendPQExpBuffer(q,
3675 3676 3677 3678 3679 3680 3681 3682 3683
						  "CREATE OPERATOR %s "
						  "(PROCEDURE = %s %s%s%s%s%s%s%s%s%s);\n",
						  oprinfo[i].oprname,
						  oprinfo[i].oprcode,
						  leftarg->data,
						  rightarg->data,
						  commutator->data,
						  negator->data,
						  restrictor->data,
B
Bruce Momjian 已提交
3684
		  (strcmp(oprinfo[i].oprcanhash, "t") == 0) ? ",\n\tHASHES" : "",
3685 3686 3687
						  join->data,
						  sort1->data,
						  sort2->data);
3688

B
Bruce Momjian 已提交
3689
		ArchiveEntry(fout, oprinfo[i].oid, oprinfo[i].oprname, "OPERATOR", NULL,
B
Bruce Momjian 已提交
3690
				q->data, delq->data, "", oprinfo[i].usename, NULL, NULL);
3691
	}
3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702

	destroyPQExpBuffer(q);
	destroyPQExpBuffer(delq);
	destroyPQExpBuffer(leftarg);
	destroyPQExpBuffer(rightarg);
	destroyPQExpBuffer(commutator);
	destroyPQExpBuffer(negator);
	destroyPQExpBuffer(restrictor);
	destroyPQExpBuffer(join);
	destroyPQExpBuffer(sort1);
	destroyPQExpBuffer(sort2);
3703 3704 3705 3706
}

/*
 * dumpAggs
3707
 *	  writes out to fout the queries to create all the user-defined aggregates
3708 3709 3710
 *
 */
void
B
Bruce Momjian 已提交
3711
dumpAggs(Archive *fout, AggInfo *agginfo, int numAggs,
3712
		 TypeInfo *tinfo, int numTypes)
3713
{
B
Bruce Momjian 已提交
3714
	int			i;
3715
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3716 3717
	PQExpBuffer delq = createPQExpBuffer();
	PQExpBuffer aggSig = createPQExpBuffer();
3718
	PQExpBuffer details = createPQExpBuffer();
3719 3720 3721

	for (i = 0; i < numAggs; i++)
	{
B
Bruce Momjian 已提交
3722
		char	   *name;
3723

3724
		resetPQExpBuffer(details);
B
Hi, all  
Bruce Momjian 已提交
3725

3726
		/* skip all the builtin oids */
3727 3728 3729 3730 3731 3732 3733 3734 3735
		if ( oidle( atooid(agginfo[i].oid), g_last_builtin_oid) )
			continue;

		resetPQExpBuffer(aggSig);
		appendPQExpBuffer(aggSig, "%s(%s)", agginfo[i].aggname,
						  findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype, zeroAsOpaque + useBaseTypeName));

		if (!agginfo[i].convertok)
		{
3736 3737 3738
			write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
					  aggSig->data);

3739
			resetPQExpBuffer(q);
3740
			appendPQExpBuffer(q, "-- WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
3741 3742 3743
									aggSig->data);
			ArchiveEntry(fout, agginfo[i].oid, aggSig->data, "WARNING", NULL,
					q->data, "" /* Del */, "", agginfo[i].usename, NULL, NULL);
3744
			continue;
3745
		}
3746

3747 3748 3749
		name = findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype, zeroAsAny + useBaseTypeName);
		if (name == NULL)
		{
3750 3751 3752 3753 3754 3755 3756 3757 3758 3759
			write_msg(NULL, "WARNING: aggregate function \"%s\" (oid %s) not dumped\n",
					  agginfo[i].aggname, agginfo[i].oid);
			write_msg(NULL, "reason: aggbasetype (oid %s) not found\n",
					  agginfo[i].aggbasetype);

			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "-- WARNING: aggregate function \"%s\" (oid %s) not dumped\n", agginfo[i].aggname, agginfo[i].oid);
			appendPQExpBuffer(q, "-- reason: aggbasetype (oid %s) not found\n", agginfo[i].aggbasetype);
			ArchiveEntry(fout, agginfo[i].oid, aggSig->data, "WARNING", NULL,
						 q->data, "" /* Del */, "", agginfo[i].usename, NULL, NULL);
3760 3761 3762
			continue;
		}
		appendPQExpBuffer(details, "BASETYPE = %s, ", name);
3763

3764 3765 3766
		name = findTypeByOid(tinfo, numTypes, agginfo[i].aggtranstype, zeroAsOpaque + useBaseTypeName);
		if (name == NULL)
		{
3767 3768 3769 3770 3771 3772 3773 3774 3775 3776
			write_msg(NULL, "WARNING: aggregate function \"%s\" (oid %s) not dumped\n",
					  agginfo[i].aggname, agginfo[i].oid);
			write_msg(NULL, "reason: aggtranstype (oid %s) not found\n",
					  agginfo[i].aggtranstype);

			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "-- WARNING: aggregate function \"%s\" (oid %s) not dumped\n", agginfo[i].aggname, agginfo[i].oid);
			appendPQExpBuffer(q, "-- reason: aggtranstype (oid %s) not found\n", agginfo[i].aggtranstype);
			ArchiveEntry(fout, agginfo[i].oid, aggSig->data, "WARNING", NULL,
						 q->data, "" /* Del */, "", agginfo[i].usename, NULL, NULL);
3777 3778
			continue;
		}
3779 3780
		appendPQExpBuffer(details,
						  "SFUNC = %s, STYPE = %s",
3781
						  agginfo[i].aggtransfn, name);
3782

3783
		if (agginfo[i].agginitval)
3784 3785
		{
			appendPQExpBuffer(details, ", INITCOND = ");
3786
			formatStringLiteral(details, agginfo[i].agginitval, CONV_ALL);
3787
		}
3788

B
Hi, all  
Bruce Momjian 已提交
3789
		if (!(strcmp(agginfo[i].aggfinalfn, "-") == 0))
3790 3791
			appendPQExpBuffer(details, ", FINALFUNC = %s",
							  agginfo[i].aggfinalfn);
3792

B
Bruce Momjian 已提交
3793 3794
		resetPQExpBuffer(delq);
		appendPQExpBuffer(delq, "DROP AGGREGATE %s;\n", aggSig->data);
3795

B
Hi, all  
Bruce Momjian 已提交
3796
		resetPQExpBuffer(q);
3797
		appendPQExpBuffer(q, "CREATE AGGREGATE %s ( %s );\n",
3798
						  agginfo[i].aggname,
3799
						  details->data);
3800

B
Bruce Momjian 已提交
3801
		ArchiveEntry(fout, agginfo[i].oid, aggSig->data, "AGGREGATE", NULL,
B
Bruce Momjian 已提交
3802
				q->data, delq->data, "", agginfo[i].usename, NULL, NULL);
B
Bruce,  
Bruce Momjian 已提交
3803 3804 3805 3806

		/*** Dump Aggregate Comments ***/

		resetPQExpBuffer(q);
3807
		appendPQExpBuffer(q, "AGGREGATE %s %s", agginfo[i].aggname,
3808
						  findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype, zeroAsOpaque + useBaseTypeName));
3809
		dumpComment(fout, q->data, agginfo[i].oid, "pg_aggregate", 0, NULL);
3810
	}
3811 3812 3813 3814 3815

	destroyPQExpBuffer(q);
	destroyPQExpBuffer(delq);
	destroyPQExpBuffer(aggSig);
	destroyPQExpBuffer(details);
3816 3817
}

3818 3819 3820 3821 3822
/*
 * These are some support functions to fix the acl problem of pg_dump
 *
 * Matthew C. Aycock 12/02/97
 */
3823 3824 3825

/* Append a keyword to a keyword list, inserting comma if needed.
 * Caller must make aclbuf big enough for all possible keywords.
3826
 */
3827
static void
B
Bruce Momjian 已提交
3828
AddAcl(char *aclbuf, const char *keyword)
3829
{
3830 3831 3832
	if (*aclbuf)
		strcat(aclbuf, ",");
	strcat(aclbuf, keyword);
3833
}
3834

3835
/*
3836
 * This will take a string of 'arwR' and return a malloced,
3837 3838
 * comma delimited string of SELECT,INSERT,UPDATE,DELETE,RULE
 */
V
Vadim B. Mikheev 已提交
3839
static char *
3840
GetPrivileges(Archive *AH, const char *s)
3841
{
3842
	char		aclbuf[100];
3843

3844
	aclbuf[0] = '\0';
3845

B
Bruce Momjian 已提交
3846
	if (strchr(s, 'a'))
3847
		AddAcl(aclbuf, "INSERT");
3848

B
Bruce Momjian 已提交
3849
	if (strchr(s, 'r'))
3850
		AddAcl(aclbuf, "SELECT");
3851

3852
	if (strchr(s, 'R'))
3853
		AddAcl(aclbuf, "RULE");
3854

3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870
	if (AH->remoteVersion >= 70200)
	{
		if (strchr(s, 'w'))
			AddAcl(aclbuf, "UPDATE");
		if (strchr(s, 'd'))
			AddAcl(aclbuf, "DELETE");
		if (strchr(s, 'x'))
			AddAcl(aclbuf, "REFERENCES");
		if (strchr(s, 't'))
			AddAcl(aclbuf, "TRIGGER");
	}
	else
	{
		if (strchr(s, 'w'))
			AddAcl(aclbuf, "UPDATE,DELETE");
	}
3871

3872
	return strdup(aclbuf);
3873
}
3874

B
Bruce Momjian 已提交
3875
/*
B
Bruce Momjian 已提交
3876
 * The name says it all; a function to append a string is the dest
B
Bruce Momjian 已提交
3877 3878
 * is big enough. If not, it does a realloc.
 */
B
Bruce Momjian 已提交
3879 3880
static void
strcatalloc(char **dest, int *dSize, char *src)
B
Bruce Momjian 已提交
3881
{
B
Bruce Momjian 已提交
3882 3883 3884 3885 3886 3887 3888 3889 3890 3891
	int			dLen = strlen(*dest);
	int			sLen = strlen(src);

	if ((dLen + sLen) >= *dSize)
	{
		*dSize = (dLen + sLen) * 2;
		*dest = realloc(*dest, *dSize);
	}
	strcpy(*dest + dLen, src);
}
B
Bruce Momjian 已提交
3892 3893


B
Bruce Momjian 已提交
3894 3895
/*
 * dumpACL:
3896 3897
 *	  Write out grant/revoke information
 *	  Called for sequences and tables
B
Bruce Momjian 已提交
3898 3899
 */

3900
static void
B
Bruce Momjian 已提交
3901
dumpACL(Archive *fout, TableInfo tbinfo)
B
Bruce Momjian 已提交
3902
{
B
Bruce Momjian 已提交
3903 3904
	const char *acls = tbinfo.relacl;
	char	   *aclbuf,
B
Bruce Momjian 已提交
3905 3906 3907
			   *tok,
			   *eqpos,
			   *priv;
3908
	char	   *objoid;
B
Bruce Momjian 已提交
3909
	char	   *sql;
B
Bruce Momjian 已提交
3910
	char		tmp[1024];
B
Bruce Momjian 已提交
3911
	int			sSize = 4096;
3912 3913 3914 3915

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

B
Bruce Momjian 已提交
3916 3917 3918
	/*
	 * Allocate a larginsh buffer for the output SQL.
	 */
B
Bruce Momjian 已提交
3919
	sql = (char *) malloc(sSize);
B
Bruce Momjian 已提交
3920

B
Bruce Momjian 已提交
3921 3922 3923
	/*
	 * Revoke Default permissions for PUBLIC. Is this actually necessary,
	 * or is it just a waste of time?
3924
	 */
B
Bruce Momjian 已提交
3925
	sprintf(sql, "REVOKE ALL on %s from PUBLIC;\n",
3926
			fmtId(tbinfo.relname, force_quotes));
3927 3928 3929

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

3931 3932
	/* Scan comma-separated ACL items */
	for (tok = strtok(aclbuf, ","); tok != NULL; tok = strtok(NULL, ","))
3933
	{
3934

B
Bruce Momjian 已提交
3935 3936 3937
		/*
		 * Token may start with '{' and/or '"'.  Actually only the start
		 * of the string should have '{', but we don't verify that.
3938 3939 3940 3941 3942 3943 3944 3945
		 */
		if (*tok == '{')
			tok++;
		if (*tok == '"')
			tok++;

		/* User name is string up to = in tok */
		eqpos = strchr(tok, '=');
B
Bruce Momjian 已提交
3946
		if (!eqpos)
B
Bruce Momjian 已提交
3947
		{
3948 3949 3950
			write_msg(NULL, "could not parse ACL list ('%s') for relation %s\n",
					  acls, tbinfo.relname);
			exit_nicely();
B
Bruce Momjian 已提交
3951 3952
		}

B
Bruce Momjian 已提交
3953 3954 3955 3956
		/*
		 * Parse the privileges (right-hand side).	Skip if there are
		 * none.
		 */
3957
		priv = GetPrivileges(fout, eqpos + 1);
3958
		if (*priv)
3959
		{
B
Bruce Momjian 已提交
3960
			sprintf(tmp, "GRANT %s on %s to ",
3961
					priv, fmtId(tbinfo.relname, force_quotes));
B
Bruce Momjian 已提交
3962
			strcatalloc(&sql, &sSize, tmp);
B
Bruce Momjian 已提交
3963 3964 3965

			/*
			 * Note: fmtId() can only be called once per printf, so don't
3966 3967 3968 3969 3970
			 * try to merge printing of username into the above printf.
			 */
			if (eqpos == tok)
			{
				/* Empty left-hand side means "PUBLIC" */
B
Bruce Momjian 已提交
3971
				strcatalloc(&sql, &sSize, "PUBLIC;\n");
3972
			}
3973
			else
3974 3975
			{
				*eqpos = '\0';	/* it's ok to clobber aclbuf */
3976
				if (strncmp(tok, "group ", strlen("group ")) == 0)
B
Bruce Momjian 已提交
3977
					sprintf(tmp, "GROUP %s;\n",
3978 3979
							fmtId(tok + strlen("group "), force_quotes));
				else
B
Bruce Momjian 已提交
3980 3981
					sprintf(tmp, "%s;\n", fmtId(tok, force_quotes));
				strcatalloc(&sql, &sSize, tmp);
3982
			}
3983
		}
3984
		free(priv);
B
Bruce Momjian 已提交
3985
	}
3986 3987

	free(aclbuf);
B
Bruce Momjian 已提交
3988

3989 3990 3991 3992 3993 3994
	if (tbinfo.viewdef != NULL)
		objoid = tbinfo.viewoid;
	else
		objoid = tbinfo.oid;

	ArchiveEntry(fout, objoid, tbinfo.relname, "ACL", NULL, sql, "", "", "", NULL, NULL);
B
Bruce Momjian 已提交
3995

B
Bruce Momjian 已提交
3996 3997
}

3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052
static void
_dumpTableAttr70(Archive *fout, TableInfo *tblinfo, int i, int j, PQExpBuffer q)
{
	int32				tmp_typmod;
	int					precision;
	int					scale;

	/* Show lengths on bpchar and varchar */
	if (!strcmp(tblinfo[i].typnames[j], "bpchar"))
	{
		int			len = (tblinfo[i].atttypmod[j] - VARHDRSZ);

		appendPQExpBuffer(q, "character");
		if (len > 1)
			appendPQExpBuffer(q, "(%d)",
					 tblinfo[i].atttypmod[j] - VARHDRSZ);
	}
	else if (!strcmp(tblinfo[i].typnames[j], "varchar"))
	{
		appendPQExpBuffer(q, "character varying");
		if (tblinfo[i].atttypmod[j] != -1)
		{
			appendPQExpBuffer(q, "(%d)",
					 tblinfo[i].atttypmod[j] - VARHDRSZ);
		}
	}
	else if (!strcmp(tblinfo[i].typnames[j], "numeric"))
	{
		appendPQExpBuffer(q, "numeric");
		if (tblinfo[i].atttypmod[j] != -1)
		{
			tmp_typmod = tblinfo[i].atttypmod[j] - VARHDRSZ;
			precision = (tmp_typmod >> 16) & 0xffff;
			scale = tmp_typmod & 0xffff;
			appendPQExpBuffer(q, "(%d,%d)",
							  precision, scale);
		}
	}

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

4054 4055
/*
 * dumpTables:
4056
 *	  write out to fout all the user-define tables
4057
 */
4058

4059
void
B
Bruce Momjian 已提交
4060
dumpTables(Archive *fout, TableInfo *tblinfo, int numTables,
4061
		   IndInfo *indinfo, int numIndexes,
4062 4063
		   InhInfo *inhinfo, int numInherits,
		   TypeInfo *tinfo, int numTypes, const char *tablename,
B
Bruce Momjian 已提交
4064 4065
		   const bool aclsSkip, const bool oids,
		   const bool schemaOnly, const bool dataOnly)
4066
{
4067 4068
	int			i,
				j,
B
Bruce Momjian 已提交
4069
				k;
4070
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
4071
	PQExpBuffer delq = createPQExpBuffer();
4072
	char	   *serialSeq = NULL;		/* implicit sequence name created
B
Bruce Momjian 已提交
4073 4074 4075 4076
										 * by SERIAL datatype */
	const char *serialSeqSuffix = "_id_seq";	/* suffix for implicit
												 * SERIAL sequences */
	char	  **parentRels;		/* list of names of parent relations */
4077
	int			numParents;
B
Bruce Momjian 已提交
4078
	int			actual_atts;	/* number of attrs in this CREATE statment */
4079
	char	   *reltypename;
4080
	char	   *objoid;
4081
	const char *((*commentDeps)[]);
4082

V
Vadim B. Mikheev 已提交
4083
	/* First - dump SEQUENCEs */
4084
	if (tablename && strlen(tablename) > 0)
B
Bruce Momjian 已提交
4085
	{
4086 4087
		/* XXX this code only works for serial columns named "id" */
		/* We really need dependency analysis! */
B
Bruce Momjian 已提交
4088 4089 4090 4091
		serialSeq = malloc(strlen(tablename) + strlen(serialSeqSuffix) + 1);
		strcpy(serialSeq, tablename);
		strcat(serialSeq, serialSeqSuffix);
	}
V
Vadim B. Mikheev 已提交
4092 4093 4094 4095
	for (i = 0; i < numTables; i++)
	{
		if (!(tblinfo[i].sequence))
			continue;
B
Bruce Momjian 已提交
4096
		if (!tablename || (!strcmp(tblinfo[i].relname, tablename))
B
Bruce Momjian 已提交
4097
			|| (serialSeq && !strcmp(tblinfo[i].relname, serialSeq)))
V
Vadim B. Mikheev 已提交
4098
		{
B
Bruce Momjian 已提交
4099
			/* becomeUser(fout, tblinfo[i].usename); */
4100
			dumpSequence(fout, tblinfo[i], schemaOnly, dataOnly);
4101
			if (!aclsSkip)
B
Bruce Momjian 已提交
4102
				dumpACL(fout, tblinfo[i]);
V
Vadim B. Mikheev 已提交
4103 4104
		}
	}
4105
	if (serialSeq)
B
Bruce Momjian 已提交
4106
		free(serialSeq);
4107

4108 4109
	for (i = 0; i < numTables; i++)
	{
4110
		if (tblinfo[i].sequence)/* already dumped */
V
Vadim B. Mikheev 已提交
4111
			continue;
4112

4113
		if (!tablename || (!strcmp(tblinfo[i].relname, tablename)) || (strlen(tablename) == 0))
4114 4115
		{

4116 4117
			resetPQExpBuffer(delq);
			resetPQExpBuffer(q);
4118

4119 4120 4121 4122
			/* Use the view definition if there is one */
			if (tblinfo[i].viewdef != NULL)
			{
				reltypename = "VIEW";
4123
				objoid = tblinfo[i].viewoid;
4124
				appendPQExpBuffer(delq, "DROP VIEW %s;\n", fmtId(tblinfo[i].relname, force_quotes));
4125
				appendPQExpBuffer(q, "CREATE VIEW %s as %s\n", fmtId(tblinfo[i].relname, force_quotes), tblinfo[i].viewdef);
4126 4127 4128
				commentDeps = malloc(sizeof(char*) * 2);
				(*commentDeps)[0] = strdup(objoid);
				(*commentDeps)[1] = NULL; /* end of list */
4129 4130
			}
			else
4131
			{
4132
				reltypename = "TABLE";
4133
				objoid = tblinfo[i].oid;
4134
				commentDeps = NULL;
4135 4136
				parentRels = tblinfo[i].parentRels;
				numParents = tblinfo[i].numParents;
B
Bruce Momjian 已提交
4137

4138
				appendPQExpBuffer(delq, "DROP TABLE %s;\n", fmtId(tblinfo[i].relname, force_quotes));
B
Bruce Momjian 已提交
4139

4140 4141 4142 4143 4144 4145
				appendPQExpBuffer(q, "CREATE TABLE %s (\n\t", fmtId(tblinfo[i].relname, force_quotes));
				actual_atts = 0;
				for (j = 0; j < tblinfo[i].numatts; j++)
				{
					/* Is this one of the table's own attrs ? */
					if (tblinfo[i].inhAttrs[j] == 0)
4146
					{
4147 4148 4149 4150 4151
						/* Format properly if not first attr */
						if (actual_atts > 0)
							appendPQExpBuffer(q, ",\n\t");

						/* Attr name & type */
4152 4153 4154 4155 4156 4157 4158 4159
						appendPQExpBuffer(q, "%s ", fmtId(tblinfo[i].attnames[j], force_quotes));

						if (g_fout->remoteVersion >= 70100)
						{
							appendPQExpBuffer(q, "%s", tblinfo[i].atttypedefns[j]);
						} else {
							_dumpTableAttr70(fout, tblinfo, i, j, q);
						}
4160 4161

						/* Default value */
4162
						if (tblinfo[i].adef_expr[j] != NULL && tblinfo[i].inhAttrDef[j] == 0)
4163
							appendPQExpBuffer(q, " DEFAULT %s",
B
Bruce Momjian 已提交
4164
											  tblinfo[i].adef_expr[j]);
4165 4166

						/* Not Null constraint */
4167
						if (tblinfo[i].notnull[j] && tblinfo[i].inhNotNull[j] == 0)
4168 4169 4170 4171
							appendPQExpBuffer(q, " NOT NULL");

						actual_atts++;
					}
4172
				}
B
Hi all  
Bruce Momjian 已提交
4173

4174 4175


4176 4177 4178 4179 4180 4181 4182
				/* put the CONSTRAINTS inside the table def */
				for (k = 0; k < tblinfo[i].ncheck; k++)
				{
					if (actual_atts + k > 0)
						appendPQExpBuffer(q, ",\n\t");

					appendPQExpBuffer(q, "%s",
B
Bruce Momjian 已提交
4183
									  tblinfo[i].check_expr[k]);
4184
				}
4185

4186 4187
				/* Primary Key */
				if (tblinfo[i].pkIndexOid != NULL)
4188
				{
B
Bruce Momjian 已提交
4189
					PQExpBuffer consDef;
4190 4191

					/* Find the corresponding index */
4192
					for (k = 0; k < numIndexes; k++)
4193
					{
4194 4195
						if (strcmp(indinfo[k].indexreloid,
								   tblinfo[i].pkIndexOid) == 0)
4196 4197 4198
							break;
					}

4199
					if (k >= numIndexes)
4200
					{
4201 4202
						write_msg(NULL, "dumpTables(): failed sanity check, could not find index (%s) for primary key constraint\n",
								   tblinfo[i].pkIndexOid);
4203
						exit_nicely();
4204 4205 4206 4207
					}

					consDef = getPKconstraint(&tblinfo[i], &indinfo[k]);

B
Bruce Momjian 已提交
4208
					if ((actual_atts + tblinfo[i].ncheck) > 0)
4209
						appendPQExpBuffer(q, ",\n\t");
4210 4211 4212 4213

					appendPQExpBuffer(q, "%s", consDef->data);

					destroyPQExpBuffer(consDef);
4214
				}
B
Bruce Momjian 已提交
4215

4216

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

4219
				if (numParents > 0)
B
Hi all  
Bruce Momjian 已提交
4220
				{
4221
					appendPQExpBuffer(q, "\nINHERITS (");
4222 4223 4224
					for (k = 0; k < numParents; k++)
					{
						appendPQExpBuffer(q, "%s%s",
B
Bruce Momjian 已提交
4225 4226
										  (k > 0) ? ", " : "",
									 fmtId(parentRels[k], force_quotes));
4227 4228
					}
					appendPQExpBuffer(q, ")");
B
Hi all  
Bruce Momjian 已提交
4229 4230
				}

4231 4232 4233
				if (!tblinfo[i].hasoids)
					appendPQExpBuffer(q, " WITHOUT OIDS");

4234 4235
				appendPQExpBuffer(q, ";\n");
			}
B
Bruce Momjian 已提交
4236

B
Bruce Momjian 已提交
4237 4238
			if (!dataOnly)
			{
4239

4240
				ArchiveEntry(fout, objoid, tblinfo[i].relname,
B
Bruce Momjian 已提交
4241 4242
							 reltypename, NULL, q->data, delq->data, "", tblinfo[i].usename,
							 NULL, NULL);
B
Bruce Momjian 已提交
4243

4244 4245 4246 4247
				if (!aclsSkip)
					dumpACL(fout, tblinfo[i]);

			}
4248

4249
			/* Dump Field Comments */
B
Bruce,  
Bruce Momjian 已提交
4250

4251 4252
			for (j = 0; j < tblinfo[i].numatts; j++)
			{
B
Bruce,  
Bruce Momjian 已提交
4253 4254 4255 4256
				resetPQExpBuffer(q);
				appendPQExpBuffer(q, "COLUMN %s", fmtId(tblinfo[i].relname, force_quotes));
				appendPQExpBuffer(q, ".");
				appendPQExpBuffer(q, "%s", fmtId(tblinfo[i].attnames[j], force_quotes));
4257 4258
				dumpComment(fout, q->data, tblinfo[i].oid,
							"pg_class", j+1, commentDeps);
B
Bruce,  
Bruce Momjian 已提交
4259
			}
4260

B
Bruce,  
Bruce Momjian 已提交
4261
			/* Dump Table Comments */
4262

B
Bruce,  
Bruce Momjian 已提交
4263
			resetPQExpBuffer(q);
4264
			appendPQExpBuffer(q, "%s %s", reltypename, fmtId(tblinfo[i].relname, force_quotes));
4265 4266
			dumpComment(fout, q->data, tblinfo[i].oid,
						"pg_class", 0, commentDeps);
4267

4268 4269
		}
	}
4270 4271 4272

	destroyPQExpBuffer(q);
	destroyPQExpBuffer(delq);
4273 4274
}

B
Bruce Momjian 已提交
4275 4276
static PQExpBuffer
getPKconstraint(TableInfo *tblInfo, IndInfo *indInfo)
4277
{
B
Bruce Momjian 已提交
4278 4279
	PQExpBuffer pkBuf = createPQExpBuffer();
	int			k;
4280 4281

	appendPQExpBuffer(pkBuf, "Constraint %s Primary Key (",
B
Bruce Momjian 已提交
4282
					  tblInfo->primary_key_name);
4283 4284 4285

	for (k = 0; k < INDEX_MAX_KEYS; k++)
	{
4286 4287
		int			indkey;
		const char *attname;
4288 4289 4290 4291

		indkey = atoi(indInfo->indkey[k]);
		if (indkey == InvalidAttrNumber)
			break;
4292
		attname = getAttrName(indkey, tblInfo);
4293 4294

		appendPQExpBuffer(pkBuf, "%s%s",
B
Bruce Momjian 已提交
4295 4296
						  (k == 0) ? "" : ", ",
						  fmtId(attname, force_quotes));
4297 4298 4299 4300 4301 4302 4303
	}

	appendPQExpBuffer(pkBuf, ")");

	return pkBuf;
}

4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332
/*
 * getAttrName: extract the correct name for an attribute
 *
 * The array tblInfo->attnames[] only provides names of user attributes;
 * if a system attribute number is supplied, we have to fake it.
 * We also do a little bit of bounds checking for safety's sake.
 */
static const char *
getAttrName(int attrnum, TableInfo *tblInfo)
{
	if (attrnum > 0 && attrnum <= tblInfo->numatts)
		return tblInfo->attnames[attrnum-1];
	switch (attrnum)
	{
		case SelfItemPointerAttributeNumber:
			return "ctid";
		case ObjectIdAttributeNumber:
			return "oid";
		case MinTransactionIdAttributeNumber:
			return "xmin";
		case MinCommandIdAttributeNumber:
			return "cmin";
		case MaxTransactionIdAttributeNumber:
			return "xmax";
		case MaxCommandIdAttributeNumber:
			return "cmax";
		case TableOidAttributeNumber:
			return "tableoid";
	}
4333 4334
	write_msg(NULL, "getAttrName(): invalid column number %d for table %s\n",
			   attrnum, tblInfo->relname);
4335
	exit_nicely();
4336 4337 4338
	return NULL;				/* keep compiler quiet */
}

4339
/*
4340
 * dumpIndexes:
4341
 *	  write out to fout all the user-defined indexes
4342
 */
4343
void
4344
dumpIndexes(Archive *fout, IndInfo *indinfo, int numIndexes,
4345
			TableInfo *tblinfo, int numTables, const char *tablename)
4346
{
4347 4348 4349
	int			i,
				k;
	int			tableInd;
4350
	PQExpBuffer attlist = createPQExpBuffer();
4351 4352 4353 4354
	PQExpBuffer q = createPQExpBuffer();
	PQExpBuffer delq = createPQExpBuffer();
	PQExpBuffer id1 = createPQExpBuffer();
	PQExpBuffer id2 = createPQExpBuffer();
B
Bruce Momjian 已提交
4355 4356 4357
	char	   *classname[INDEX_MAX_KEYS];
	char	   *funcname;		/* the name of the function to comput the
								 * index key from */
4358
	Oid			indclass;
4359 4360
	int			nclass;
	PGresult   *res;
4361

4362
	for (i = 0; i < numIndexes; i++)
4363 4364
	{
		tableInd = findTableByName(tblinfo, numTables,
4365 4366 4367
								   indinfo[i].indrelname);
		if (tableInd < 0)
		{
4368 4369
			write_msg(NULL, "dumpIndexes(): failed sanity check, table %s was not found\n",
					   indinfo[i].indrelname);
4370
			exit_nicely();
4371
		}
4372

4373 4374 4375
		/* Handle PK indexes */
		if (strcmp(indinfo[i].indisprimary, "t") == 0)
		{
4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392
#if 0
			/* PK: Enable this code when ALTER TABLE supports PK constraints. */

			PQExpBuffer consDef = getPKconstraint(&tblinfo[tableInd], &indinfo[i]);

			resetPQExpBuffer(attlist);

			appendPQExpBuffer(attlist, "Alter Table %s Add %s;",
							  fmtId(tblinfo[tableInd].relname, force_quotes),
							  consDef->data);

			ArchiveEntry(fout, indinfo[i].oid, tblinfo[tableInd].primary_key_name,
						 "CONSTRAINT", NULL, attlist->data, "",
						 "", tblinfo[tableInd].usename, NULL, NULL);

			destroyPQExpBuffer(consDef);
#endif
B
Bruce Momjian 已提交
4393 4394 4395 4396 4397

			/*
			 * Don't need to do anything else for this system-generated
			 * index
			 */
4398 4399 4400
			continue;
		}

4401 4402

		if (strcmp(indinfo[i].indproc, "0") == 0)
4403 4404 4405
			funcname = NULL;
		else
		{
B
Bruce Momjian 已提交
4406
			int			numFuncs;
4407 4408

			/*
4409
			 * the indproc is an oid which we use to find the name of the
4410 4411 4412 4413
			 * pg_proc.  We need to do this because getFuncs() only reads
			 * in the user-defined funcs not all the funcs.  We might not
			 * find what we want by looking in FuncInfo*
			 */
B
Hi, all  
Bruce Momjian 已提交
4414 4415
			resetPQExpBuffer(q);
			appendPQExpBuffer(q,
4416 4417 4418
							  "SELECT proname from pg_proc "
							  "where pg_proc.oid = '%s'::oid",
							  indinfo[i].indproc);
B
Hi, all  
Bruce Momjian 已提交
4419
			res = PQexec(g_conn, q->data);
4420 4421
			if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
			{
4422 4423
				write_msg(NULL, "query to get function name of oid %s failed: %s",
						  indinfo[i].indproc, PQerrorMessage(g_conn));
4424
				exit_nicely();
4425
			}
4426 4427 4428

			/* Sanity: Check we got only one tuple */
			numFuncs = PQntuples(res);
B
Bruce Momjian 已提交
4429 4430
			if (numFuncs != 1)
			{
4431 4432
				write_msg(NULL, "query to get function name of oid %s returned %d rows; expected 1\n",
						  indinfo[i].indproc, numFuncs);
4433
				exit_nicely();
4434 4435
			}

B
Bruce Momjian 已提交
4436
			funcname = strdup(PQgetvalue(res, 0, PQfnumber(res, "proname")));
4437 4438 4439 4440 4441 4442
			PQclear(res);
		}

		/* convert opclass oid(s) into names */
		for (nclass = 0; nclass < INDEX_MAX_KEYS; nclass++)
		{
B
Bruce Momjian 已提交
4443
			int			numRows;
4444

4445
			indclass = atooid(indinfo[i].indclass[nclass]);
4446 4447
			if (indclass == 0)
				break;
B
Hi, all  
Bruce Momjian 已提交
4448 4449
			resetPQExpBuffer(q);
			appendPQExpBuffer(q,
4450 4451 4452
							  "SELECT opcname from pg_opclass "
							  "where pg_opclass.oid = '%u'::oid",
							  indclass);
B
Hi, all  
Bruce Momjian 已提交
4453
			res = PQexec(g_conn, q->data);
4454 4455
			if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
			{
4456 4457
				write_msg(NULL, "query to get operator class name of oid %u failed: %s",
						  indclass, PQerrorMessage(g_conn));
4458
				exit_nicely();
4459
			}
4460 4461 4462

			/* Sanity: Check we got only one tuple */
			numRows = PQntuples(res);
B
Bruce Momjian 已提交
4463 4464
			if (numRows != 1)
			{
4465 4466
				write_msg(NULL, "query to get operator class name of oid %u returned %d rows; expected 1\n",
						  indclass, numRows);
4467
				exit_nicely();
4468 4469
			}

B
Bruce Momjian 已提交
4470
			classname[nclass] = strdup(PQgetvalue(res, 0, PQfnumber(res, "opcname")));
4471 4472 4473 4474 4475
			PQclear(res);
		}

		if (funcname && nclass != 1)
		{
4476 4477
			write_msg(NULL, "There must be exactly one OpClass for functional index \"%s\".\n",
					  indinfo[i].indexrelname);
4478
			exit_nicely();
4479 4480 4481
		}

		/* convert attribute numbers into attribute list */
B
Hi, all  
Bruce Momjian 已提交
4482 4483
		resetPQExpBuffer(attlist);
		for (k = 0; k < INDEX_MAX_KEYS; k++)
4484
		{
4485 4486
			int			indkey;
			const char *attname;
4487 4488

			indkey = atoi(indinfo[i].indkey[k]);
B
Bruce Momjian 已提交
4489
			if (indkey == InvalidAttrNumber)
4490
				break;
4491
			attname = getAttrName(indkey, &tblinfo[tableInd]);
4492
			if (funcname)
B
Hi, all  
Bruce Momjian 已提交
4493
				appendPQExpBuffer(attlist, "%s%s",
4494 4495
								  (k == 0) ? "" : ", ",
								  fmtId(attname, force_quotes));
4496 4497 4498 4499
			else
			{
				if (k >= nclass)
				{
4500
					write_msg(NULL, "no operator class found for column \"%s\" of index \"%s\"\n",
4501
							attname, indinfo[i].indexrelname);
4502
					exit_nicely();
4503
				}
B
Hi, all  
Bruce Momjian 已提交
4504 4505 4506 4507 4508
				resetPQExpBuffer(id1);
				resetPQExpBuffer(id2);
				appendPQExpBuffer(id1, fmtId(attname, force_quotes));
				appendPQExpBuffer(id2, fmtId(classname[k], force_quotes));
				appendPQExpBuffer(attlist, "%s%s %s",
4509 4510
								  (k == 0) ? "" : ", ",
								  id1->data, id2->data);
4511 4512 4513 4514
				free(classname[k]);
			}
		}

B
Bruce Momjian 已提交
4515
		if (!tablename || (strcmp(indinfo[i].indrelname, tablename) == 0) || (strlen(tablename) == 0))
4516
		{
B
Hi, all  
Bruce Momjian 已提交
4517 4518 4519 4520
			resetPQExpBuffer(id1);
			resetPQExpBuffer(id2);
			appendPQExpBuffer(id1, fmtId(indinfo[i].indexrelname, force_quotes));
			appendPQExpBuffer(id2, fmtId(indinfo[i].indrelname, force_quotes));
4521

B
Bruce Momjian 已提交
4522 4523
			resetPQExpBuffer(delq);
			appendPQExpBuffer(delq, "DROP INDEX %s;\n", id1->data);
4524

B
Bruce Momjian 已提交
4525 4526
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "CREATE %s INDEX %s on %s using %s (",
B
Bruce Momjian 已提交
4527 4528 4529 4530
			  (strcmp(indinfo[i].indisunique, "t") == 0) ? "UNIQUE" : "",
							  id1->data,
							  id2->data,
							  indinfo[i].indamname);
4531 4532
			if (funcname)
			{
4533
				/* need 2 printf's here cuz fmtId has static return area */
B
Bruce Momjian 已提交
4534
				appendPQExpBuffer(q, " %s", fmtId(funcname, false));
4535
				appendPQExpBuffer(q, " (%s) %s )", attlist->data,
B
Bruce Momjian 已提交
4536
								  fmtId(classname[0], force_quotes));
4537 4538 4539 4540
				free(funcname);
				free(classname[0]);
			}
			else
4541 4542
				appendPQExpBuffer(q, " %s )", attlist->data);
				
4543
			if (strcmp(indinfo[i].indhaspred, "t") == 0)
4544
			{
4545
				/* There is an index predicate, so fetch and dump it */
4546 4547 4548
				int numRows;
				PQExpBuffer pred = createPQExpBuffer();
				
4549 4550
				appendPQExpBuffer(pred, "SELECT pg_get_expr(indpred,indrelid) as pred FROM pg_index WHERE indexrelid = %s",
								  indinfo[i].indexreloid);
4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575
				res = PQexec(g_conn, pred->data);
				if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
				{
					fprintf(stderr, "dumpIndices(): SELECT (indpred) failed.  "
							"Explanation from backend: '%s'.\n",
							PQerrorMessage(g_conn));
					exit_nicely();
				}
	
				/* Sanity: Check we got only one tuple */
				numRows = PQntuples(res);
				if (numRows != 1)
				{
					fprintf(stderr, "dumpIndices(): SELECT (indpred) for index %s returned %d tuples. Expected 1.\n",
							indinfo[i].indrelname, numRows);
					exit_nicely();
				}
	
				appendPQExpBuffer(q, " WHERE %s",
								  PQgetvalue(res, 0, PQfnumber(res, "pred")));

				PQclear(res);
				destroyPQExpBuffer( pred );
			}
			appendPQExpBuffer(q, ";\n");
B
Bruce,  
Bruce Momjian 已提交
4576

4577 4578 4579 4580 4581
			/*
			 * 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.
			 */
4582 4583
			ArchiveEntry(fout, indinfo[i].indexreloid, id1->data,
						 "INDEX", NULL, q->data, delq->data,
B
Bruce Momjian 已提交
4584
						 "", tblinfo[tableInd].usename, NULL, NULL);
B
Bruce Momjian 已提交
4585

4586
			/* Dump Index Comments */
B
Bruce,  
Bruce Momjian 已提交
4587 4588
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "INDEX %s", id1->data);
4589 4590
			dumpComment(fout, q->data, indinfo[i].indexreloid,
						"pg_class", 0, NULL);
4591

4592 4593
		}
	}
4594

4595 4596 4597 4598 4599
	destroyPQExpBuffer(attlist);
	destroyPQExpBuffer(q);
	destroyPQExpBuffer(delq);
	destroyPQExpBuffer(id1);
	destroyPQExpBuffer(id2);
4600
}
4601

4602
/*
B
Bruce Momjian 已提交
4603
 * dumpTuples
4604 4605 4606 4607 4608
 *	  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
4609
 *	  in PostgreSQL.
4610 4611 4612 4613
 *
 * the attrmap passed in tells how to map the attributes copied in to the
 * attributes copied out
 */
4614
#ifdef NOT_USED
4615
void
4616
dumpTuples(PGresult *res, FILE *fout, int *attrmap)
4617
{
4618 4619 4620 4621
	int			j,
				k;
	int			m,
				n;
B
Bruce Momjian 已提交
4622
	char	  **outVals = NULL; /* values to copy out */
4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641

	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++)
			{
4642
				char	   *pval = outVals[k];
4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662

				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);
	}
4663
}
4664

4665
#endif
4666

4667 4668 4669 4670
/*
 * setMaxOid -
 * find the maximum oid and generate a COPY statement to set it
*/
4671

4672
static void
B
Bruce Momjian 已提交
4673
setMaxOid(Archive *fout)
4674
{
B
Bruce Momjian 已提交
4675 4676
	PGresult   *res;
	Oid			max_oid;
B
Bruce Momjian 已提交
4677
	char		sql[1024];
4678

4679
	res = PQexec(g_conn, "CREATE TEMPORARY TABLE pgdump_oid (dummy int4)");
4680 4681 4682
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
4683
		write_msg(NULL, "could not create pgdump_oid table: %s", PQerrorMessage(g_conn));
4684
		exit_nicely();
4685 4686
	}
	PQclear(res);
4687
	res = PQexec(g_conn, "INSERT INTO pgdump_oid VALUES (0)");
4688 4689 4690
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
4691
		write_msg(NULL, "could not insert into pgdump_oid table: %s", PQerrorMessage(g_conn));
4692
		exit_nicely();
4693
	}
4694
	max_oid = PQoidValue(res);
4695 4696
	if (max_oid == 0)
	{
4697
		write_msg(NULL, "inserted invalid oid\n");
4698
		exit_nicely();
4699 4700
	}
	PQclear(res);
4701
	res = PQexec(g_conn, "DROP TABLE pgdump_oid;");
4702 4703 4704
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
4705
		write_msg(NULL, "could not drop pgdump_oid table: %s", PQerrorMessage(g_conn));
4706
		exit_nicely();
4707 4708 4709
	}
	PQclear(res);
	if (g_verbose)
4710
		write_msg(NULL, "maximum system oid is %u\n", max_oid);
4711 4712 4713
	snprintf(sql, 1024,
			 "CREATE TEMPORARY TABLE pgdump_oid (dummy int4);\n"
			 "COPY pgdump_oid WITH OIDS FROM stdin;\n"
4714
			 "%u\t0\n"
4715 4716 4717
			 "\\.\n"
			 "DROP TABLE pgdump_oid;\n",
			 max_oid);
B
Bruce Momjian 已提交
4718

4719
	ArchiveEntry(fout, "0", "Max OID", "<Init>", NULL, sql, "", "", "", NULL, NULL);
4720
}
4721 4722 4723

/*
 * findLastBuiltInOid -
4724
 * find the last built in oid
4725 4726
 * we do this by retrieving datlastsysoid from the pg_database entry for this database,
 */
4727

4728
static Oid
4729
findLastBuiltinOid_V71(const char *dbname)
4730
{
B
Bruce Momjian 已提交
4731
	PGresult   *res;
4732
	int			ntups;
4733
	Oid			last_oid;
4734 4735 4736
	PQExpBuffer query = createPQExpBuffer();

	resetPQExpBuffer(query);
4737
	appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
4738
	formatStringLiteral(query, dbname, CONV_ALL);
4739

4740
	res = PQexec(g_conn, query->data);
4741 4742 4743
	if (res == NULL ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
4744
		write_msg(NULL, "error in finding the last system oid: %s", PQerrorMessage(g_conn));
4745
		exit_nicely();
4746 4747
	}
	ntups = PQntuples(res);
4748
	if (ntups < 1)
4749
	{
4750
		write_msg(NULL, "missing pg_database entry for this database\n");
4751
		exit_nicely();
4752 4753 4754
	}
	if (ntups > 1)
	{
4755
		write_msg(NULL, "found more than one pg_database entry for this database\n");
4756
		exit_nicely();
4757
	}
4758
	last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
4759
	PQclear(res);
4760
	destroyPQExpBuffer(query);
4761
	return last_oid;
4762 4763
}

4764 4765 4766 4767 4768 4769 4770
/*
 * findLastBuiltInOid -
 * find the last built in oid
 * we do this by looking up the oid of 'template1' in pg_database,
 * this is probably not foolproof but comes close
*/

4771
static Oid
4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782
findLastBuiltinOid_V70(void)
{
	PGresult   *res;
	int			ntups;
	int			last_oid;

	res = PQexec(g_conn,
			  "SELECT oid from pg_database where datname = 'template1'");
	if (res == NULL ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
4783
		write_msg(NULL, "error in finding the template1 database: %s", PQerrorMessage(g_conn));
4784
		exit_nicely();
4785 4786 4787 4788
	}
	ntups = PQntuples(res);
	if (ntups < 1)
	{
4789
		write_msg(NULL, "could not find template1 database entry in the pg_database table\n");
4790
		exit_nicely();
4791 4792 4793
	}
	if (ntups > 1)
	{
4794
		write_msg(NULL, "found more than one template1 database entry in the pg_database table\n");
4795
		exit_nicely();
4796 4797 4798 4799 4800
	}
	last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
	PQclear(res);
	return last_oid;
}
4801

4802
static void
4803
dumpSequence(Archive *fout, TableInfo tbinfo, const bool schemaOnly, const bool dataOnly)
4804
{
4805
	PGresult   *res;
4806 4807 4808 4809 4810 4811
	char	   *last,
			   *incby,
			   *maxv,
			   *minv,
			   *cache;
	bool		cycled,
B
Bruce Momjian 已提交
4812
				called;
4813
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
4814
	PQExpBuffer delqry = createPQExpBuffer();
4815

B
Hi, all  
Bruce Momjian 已提交
4816
	appendPQExpBuffer(query,
4817
			"SELECT sequence_name, last_value, increment_by, max_value, "
4818 4819
				  "min_value, cache_value, is_cycled, is_called from %s",
					  fmtId(tbinfo.relname, force_quotes));
4820

B
Hi, all  
Bruce Momjian 已提交
4821
	res = PQexec(g_conn, query->data);
4822 4823
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
4824
		write_msg(NULL, "query to get data of sequence \"%s\" failed: %s", tbinfo.relname, PQerrorMessage(g_conn));
4825
		exit_nicely();
4826 4827 4828 4829
	}

	if (PQntuples(res) != 1)
	{
4830 4831
		write_msg(NULL, "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
				   tbinfo.relname, PQntuples(res));
4832
		exit_nicely();
4833 4834 4835 4836
	}

	if (strcmp(PQgetvalue(res, 0, 0), tbinfo.relname) != 0)
	{
4837 4838
		write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
				   tbinfo.relname, PQgetvalue(res, 0, 0));
4839
		exit_nicely();
4840 4841
	}

4842 4843 4844 4845 4846 4847 4848
	last = PQgetvalue(res, 0, 1);
	incby = PQgetvalue(res, 0, 2);
	maxv = PQgetvalue(res, 0, 3);
	minv = PQgetvalue(res, 0, 4);
	cache = PQgetvalue(res, 0, 5);
	cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
	called = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
4849

4850
	/*
B
Bruce Momjian 已提交
4851 4852
	 * The logic we use for restoring sequences is as follows: -   Add a
	 * basic CREATE SEQUENCE statement (use last_val for start if called
4853
	 * is false, else use min_val for start_val).
4854 4855 4856
	 *
	 *	Add a 'SETVAL(seq, last_val, iscalled)' at restore-time iff
	 *  we load data
4857
	 */
4858

4859 4860 4861
	if (!dataOnly)
	{
		resetPQExpBuffer(delqry);
4862 4863
		appendPQExpBuffer(delqry, "DROP SEQUENCE %s;\n",
						  fmtId(tbinfo.relname, force_quotes));
4864

4865 4866
		resetPQExpBuffer(query);
		appendPQExpBuffer(query,
4867 4868
						  "CREATE SEQUENCE %s start %s increment %s "
						  "maxvalue %s minvalue %s cache %s%s;\n",
B
Bruce Momjian 已提交
4869
						  fmtId(tbinfo.relname, force_quotes),
4870
						  (called ? minv : last),
4871
						  incby, maxv, minv, cache,
4872
						  (cycled ? " cycle" : ""));
4873

P
Philip Warner 已提交
4874
		ArchiveEntry(fout, tbinfo.oid, tbinfo.relname, "SEQUENCE", NULL,
4875 4876
					 query->data, delqry->data, "", tbinfo.usename,
					 NULL, NULL);
4877
	}
4878

4879 4880 4881 4882 4883
	if (!schemaOnly)
	{
		resetPQExpBuffer(query);
		appendPQExpBuffer(query, "SELECT setval (");
		formatStringLiteral(query, fmtId(tbinfo.relname, force_quotes), CONV_ALL);
4884 4885
		appendPQExpBuffer(query, ", %s, %s);\n",
						  last, (called ? "true" : "false"));
4886

P
Philip Warner 已提交
4887
		ArchiveEntry(fout, tbinfo.oid, tbinfo.relname, "SEQUENCE SET", NULL,
B
Bruce Momjian 已提交
4888
					 query->data, "" /* Del */ , "", "", NULL, NULL);
4889
	}
B
Bruce,  
Bruce Momjian 已提交
4890

4891 4892 4893
	if (!dataOnly)
	{
		/* Dump Sequence Comments */
B
Bruce,  
Bruce Momjian 已提交
4894

4895 4896
		resetPQExpBuffer(query);
		appendPQExpBuffer(query, "SEQUENCE %s", fmtId(tbinfo.relname, force_quotes));
4897 4898
		dumpComment(fout, query->data, tbinfo.oid,
					"pg_class", 0, NULL);
4899
	}
4900

4901 4902
	PQclear(res);

4903 4904
	destroyPQExpBuffer(query);
	destroyPQExpBuffer(delqry);
4905
}
V
Vadim B. Mikheev 已提交
4906 4907


4908
static void
B
Bruce Momjian 已提交
4909
dumpTriggers(Archive *fout, const char *tablename,
4910
			 TableInfo *tblinfo, int numTables)
V
Vadim B. Mikheev 已提交
4911
{
4912 4913 4914
	int			i,
				j;

V
Vadim B. Mikheev 已提交
4915
	if (g_verbose)
4916
		write_msg(NULL, "dumping out triggers\n");
4917

V
Vadim B. Mikheev 已提交
4918 4919
	for (i = 0; i < numTables; i++)
	{
B
Bruce Momjian 已提交
4920
		if (tablename && (strcmp(tblinfo[i].relname, tablename) != 0) && (strlen(tablename) > 0))
V
Vadim B. Mikheev 已提交
4921
			continue;
4922

V
Vadim B. Mikheev 已提交
4923 4924
		for (j = 0; j < tblinfo[i].ntrig; j++)
		{
B
Bruce Momjian 已提交
4925
			ArchiveEntry(fout, tblinfo[i].triggers[j].oid, tblinfo[i].triggers[j].tgname,
B
Bruce Momjian 已提交
4926 4927
				   "TRIGGER", NULL, tblinfo[i].triggers[j].tgsrc, "", "",
						 tblinfo[i].usename, NULL, NULL);
4928 4929
			dumpComment(fout, tblinfo[i].triggers[j].tgcomment, tblinfo[i].triggers[j].oid,
						"pg_trigger", 0, NULL);
V
Vadim B. Mikheev 已提交
4930 4931 4932
		}
	}
}
4933 4934


4935
static void
B
Bruce Momjian 已提交
4936
dumpRules(Archive *fout, const char *tablename,
B
Bruce Momjian 已提交
4937
		  TableInfo *tblinfo, int numTables)
4938
{
B
Bruce Momjian 已提交
4939 4940 4941 4942
	PGresult   *res;
	int			nrules;
	int			i,
				t;
4943
	PQExpBuffer query = createPQExpBuffer();
4944

B
Bruce Momjian 已提交
4945
	int			i_definition;
4946
	int			i_oid;
4947
	int			i_owner;
4948
	int			i_rulename;
4949 4950

	if (g_verbose)
4951
		write_msg(NULL, "dumping out rules\n");
4952 4953 4954 4955 4956 4957

	/*
	 * For each table we dump
	 */
	for (t = 0; t < numTables; t++)
	{
B
Bruce Momjian 已提交
4958
		if (tablename && (strcmp(tblinfo[t].relname, tablename) != 0) && (strlen(tablename) > 0))
4959 4960 4961
			continue;

		/*
B
Bruce Momjian 已提交
4962 4963
		 * Get all rules defined for this table We include pg_rules in the
		 * cross since it filters out all view rules (pjw 15-Sep-2000).
4964 4965
		 *
		 * XXXX: Use LOJ here
4966
		 */
B
Hi, all  
Bruce Momjian 已提交
4967
		resetPQExpBuffer(query);
4968
		appendPQExpBuffer(query, "SELECT definition,"
4969
						  "   (select usename from pg_user where pg_class.relowner = usesysid) AS viewowner, "
4970 4971
						  "   pg_rewrite.oid, pg_rewrite.rulename "
						  "FROM pg_rewrite, pg_class, pg_rules "
4972
						  "WHERE pg_class.relname = ");
4973
		formatStringLiteral(query, tblinfo[t].relname, CONV_ALL);
4974
		appendPQExpBuffer(query,
4975 4976
						  "    AND pg_rewrite.ev_class = pg_class.oid "
						  "    AND pg_rules.tablename = pg_class.relname "
B
Bruce Momjian 已提交
4977
					   "    AND pg_rules.rulename = pg_rewrite.rulename "
4978
						  "ORDER BY pg_rewrite.oid");
B
Hi, all  
Bruce Momjian 已提交
4979
		res = PQexec(g_conn, query->data);
4980 4981 4982
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
4983 4984
			write_msg(NULL, "query to get rules associated with table \"%s\" failed: %s",
					   tblinfo[t].relname, PQerrorMessage(g_conn));
4985
			exit_nicely();
4986 4987 4988 4989
		}

		nrules = PQntuples(res);
		i_definition = PQfnumber(res, "definition");
4990
		i_owner = PQfnumber(res, "viewowner");
B
Bruce,  
Bruce Momjian 已提交
4991 4992
		i_oid = PQfnumber(res, "oid");
		i_rulename = PQfnumber(res, "rulename");
4993 4994 4995 4996

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

4998 4999
		for (i = 0; i < nrules; i++)
		{
B
Bruce Momjian 已提交
5000
			ArchiveEntry(fout, PQgetvalue(res, i, i_oid), PQgetvalue(res, i, i_rulename),
B
Bruce Momjian 已提交
5001 5002
						 "RULE", NULL, PQgetvalue(res, i, i_definition),
						 "", "", PQgetvalue(res, i, i_owner), NULL, NULL);
5003

B
Bruce,  
Bruce Momjian 已提交
5004 5005 5006 5007
			/* Dump rule comments */

			resetPQExpBuffer(query);
			appendPQExpBuffer(query, "RULE %s", fmtId(PQgetvalue(res, i, i_rulename), force_quotes));
5008 5009
			dumpComment(fout, query->data, PQgetvalue(res, i, i_oid),
						"pg_rewrite", 0, NULL);
5010

B
Bruce,  
Bruce Momjian 已提交
5011 5012
		}

5013 5014
		PQclear(res);
	}
5015 5016

	destroyPQExpBuffer(query);
5017
}