pg_dump.c 131.6 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 16 17 18 19
 *	pg_dump will read the system catalogs in a database and
 *	dump out a script that reproduces
 *	the schema of the database in terms of
 *		  user-defined types
 *		  user-defined functions
 *		  tables
 *		  indices
 *		  aggregates
 *		  operators
 *		  ACL - grant/revoke
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.208 2001/05/17 21:12:48 petere Exp $
26
 *
27
 * Modifications - 6/10/96 - dave@bensoft.com - version 1.13.dhb
28
 *
29 30 31 32
 *	 Applied 'insert string' patch from "Marc G. Fournier" <scrappy@ki.net>
 *	 Added '-t table' option
 *	 Added '-a' option
 *	 Added '-da' option
33
 *
34 35
 * Modifications - 6/12/96 - dave@bensoft.com - version 1.13.dhb.2
 *
36 37 38
 *	 - Fixed dumpTable output to output lengths for char and varchar types!
 *	 - Added single. quote to twin single quote expansion for 'insert' string
 *	   mode.
39
 *
40 41
 * Modifications - 7/26/96 - asussman@vidya.com
 *
42
 *	 - Fixed ouput lengths for char and varchar type where the length is variable (-1)
43
 *
44 45
 * Modifications - 6/1/97 - igor@sba.miami.edu
 * - Added functions to free allocated memory used for retrieving
46 47
 *	 indices,tables,inheritance,types,functions and aggregates.
 *	 No more leaks reported by Purify.
48 49 50
 *
 *
 * Modifications - 1/26/98 - pjlobo@euitt.upm.es
51
 *		 - Added support for password authentication
B
Bruce Momjian 已提交
52 53 54 55 56 57
 *
 * Modifications - 28-Jun-2000 - Philip Warner pjw@rhyme.com.au
 *		 - Used custom IO routines to allow for more
 *		   output formats and simple rearrangement of order.
 *		 - Discouraged operations more appropriate to the 'restore'
 *		   operation. (eg. -c "clear schema" - now always dumps
B
Bruce Momjian 已提交
58
 *		   commands, but pg_restore can be told not to output them).
B
Bruce Momjian 已提交
59 60 61 62 63
 *		 - Added RI warnings to the 'as insert strings' output mode
 *		 - Added a small number of comments
 *		 - Added a -Z option for compression level on compressed formats
 *		 - Restored '-f' in usage output
 *
64 65 66 67 68
 *
 * Modifications - 17-Jul-2000 - Philip Warner pjw@rhyme.com.au
 *		 - Support for BLOB output.
 *		 - Sort archive by OID, put some items at end (out of OID order)
 *
69 70
 * Modifications - 28-Jul-2000 - pjw@rhyme.com.au (1.45)
 *
B
Bruce Momjian 已提交
71
 *		Added --create, --no-owner, --superuser, --no-reconnect (pg_dump & pg_restore)
72 73 74 75 76 77 78 79 80 81
 *		Added code to dump 'Create Schema' statement (pg_dump)
 *		Don't bother to disable/enable triggers if we don't have a superuser (pg_restore)
 *		Cleaned up code for reconnecting to database.
 *		Force a reconnect as superuser before enabling/disabling triggers.
 *
 * Modifications - 31-Jul-2000 - pjw@rhyme.com.au (1.46, 1.47)
 *		Added & Removed --throttle (pg_dump)
 *		Fixed minor bug in language dumping code: expbuffres were not being reset.
 *		Fixed version number initialization in _allocAH (pg_backup_archiver.c)
 *
B
Bruce Momjian 已提交
82
 * Modifications - 14-Sep-2000 - pjw@rhyme.com.au
83
 *		Use symbols for tests on relkind (ie. use RELKIND_VIEW, not 'v')
B
Bruce Momjian 已提交
84 85
 *		Support for relkind = RELKIND_VIEW.
 *		Fix bug in support for -b option (== --blobs).
86 87 88 89
 *		Dump views as views (using 'create view').
 *		Remove 'isViewRule' since we check the relkind when getting tables.
 *		Now uses temp table 'pgdump_oid' rather than 'pg_dump_oid' (errors otherwise).
 *
90 91 92 93
 * Modifications - 02-Oct-2000 - pjw@rhyme.com.au
 *
 *	  - Be more paranoid when getting views: call get_viewdef in separate statement
 *		so we can be more informative in error messages.
B
Bruce Momjian 已提交
94 95
 *	  - Support for 'isstrict' procedure attribute.
 *	  - Disable --blobs and --table since (a) it's a pain to get ONLY the blobs for the
96 97 98
 *		table with the currently implementation, and (b) it's not clear how to restore
 *		a partial BLOB backup (given the current OID-based BLOB implementation).
 *
99
 * Modifications - 04-Jan-2001 - pjw@rhyme.com.au
100 101 102 103
 *
 *	  - Check ntuples == 1 for various SELECT statements.
 *	  - Fix handling of --tables=* (multiple tables never worked properly, AFAICT)
 *
104 105
 * Modifications - 13-Feb-2001 - pjw@rhyme.com.au
 *
B
Bruce Momjian 已提交
106 107 108
 *	  - Fix help output: replace 'f' with 't' and change desc.
 *	  - Add extra arg to formatStringLiteral to specify how to handle LF & TAB.
 *		I opted for encoding them except in procedure bodies.
109 110
 *	  - Dump relevant parts of sequences only when doing schemaOnly & dataOnly
 *	  - Prevent double-dumping of sequences when dataOnly.
P
Philip Warner 已提交
111
 *
B
Bruce Momjian 已提交
112
 * Modifications - 19-Mar-2001 - pjw@rhyme.com.au
P
Philip Warner 已提交
113 114 115 116 117
 *
 *	  - Remove fmtId calls for all ArchiveEntry name fields. This fixes
 *		quoting problems in trigger enable/disable code for mixed case
 *		table names, and avoids commands like 'pg_restore -t '"TblA"''
 *
118 119 120 121 122 123 124
 * Modifications - 31-Mar-2001 - pjw@rhyme.com.au
 *
 *	  - Dump dependency information in dumpType. This is necessary
 *		because placeholder types will have an OID less than the
 *		OID of the type functions, but type must be created after 
 *		the functions.
 *
125 126 127 128 129
 * Modifications - 4-Apr-2001 - pjw@rhyme.com.au
 *
 *	  - Don't dump CHECK constraints with same source and names both
 *		starting with '$'.
 *
130 131 132 133 134 135
 * Modifications - 10-May-2001 - pjw@rhyme.com.au
 *
 *	  - Don't dump COMMENTs in data-only dumps
 *	  - Fix view dumping SQL for V7.0
 *	  - Fix bug when getting view oid with long view names
 *
136
 *-------------------------------------------------------------------------
137 138
 */

139 140 141 142 143 144 145
/*
 * 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"

146
#include <unistd.h>				/* for getopt() */
147
#include <ctype.h>
148

149 150
#include "pg_backup.h"

151 152 153 154 155 156 157 158
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif

#include "access/attnum.h"
159
#include "access/htup.h"
160
#include "catalog/pg_class.h"
V
Vadim B. Mikheev 已提交
161
#include "catalog/pg_trigger.h"
162
#include "catalog/pg_type.h"
163

164
#include "libpq-fe.h"
165
#include "libpq/libpq-fs.h"
166
#ifndef HAVE_STRDUP
167 168
#include "strdup.h"
#endif
169 170

#include "pg_dump.h"
B
Bruce Momjian 已提交
171
#include "pg_backup.h"
172

B
Bruce Momjian 已提交
173 174 175 176 177 178 179 180
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. */
181 182
} formatLiteralOptions;

B
Bruce Momjian 已提交
183
static void dumpComment(Archive *outfile, const char *target, const char *oid);
184
static void dumpSequence(Archive *fout, TableInfo tbinfo, const bool schemaOnly, const bool dataOnly);
B
Bruce Momjian 已提交
185 186
static void dumpACL(Archive *fout, TableInfo tbinfo);
static void dumpTriggers(Archive *fout, const char *tablename,
187
			 TableInfo *tblinfo, int numTables);
B
Bruce Momjian 已提交
188
static void dumpRules(Archive *fout, const char *tablename,
B
Bruce Momjian 已提交
189
		  TableInfo *tblinfo, int numTables);
190
static void formatStringLiteral(PQExpBuffer buf, const char *str, const formatLiteralOptions opts);
191
static void clearTableInfo(TableInfo *, int);
B
Bruce Momjian 已提交
192
static void dumpOneFunc(Archive *fout, FuncInfo *finfo, int i,
193
			TypeInfo *tinfo, int numTypes);
194 195
static Oid	findLastBuiltinOid_V71(const char *);
static Oid	findLastBuiltinOid_V70(void);
B
Bruce Momjian 已提交
196
static void setMaxOid(Archive *fout);
197

198 199
static void AddAcl(char *aclbuf, const char *keyword);
static char *GetPrivileges(const char *s);
V
Vadim B. Mikheev 已提交
200

B
Bruce Momjian 已提交
201 202
static int	dumpBlobs(Archive *AH, char *, void *);
static int	dumpDatabase(Archive *AH);
203
static PQExpBuffer getPKconstraint(TableInfo *tblInfo, IndInfo *indInfo);
204
static const char *getAttrName(int attrnum, TableInfo *tblInfo);
205

B
Bruce Momjian 已提交
206
extern char *optarg;
207
extern int	optind,
B
Bruce Momjian 已提交
208
			opterr;
209 210

/* global decls */
211
bool		g_verbose;			/* User wants verbose narration of our
B
Bruce Momjian 已提交
212
								 * activities. */
213
Oid			g_last_builtin_oid; /* value of the last builtin oid */
B
Bruce Momjian 已提交
214
Archive    *g_fout;				/* the script file */
B
Bruce Momjian 已提交
215 216 217
PGconn	   *g_conn;				/* the database connection */

bool		force_quotes;		/* User wants to suppress double-quotes */
218 219 220 221
bool		dumpData;			/* dump data using proper insert strings */
bool		attrNames;			/* put attr names into insert strings */
bool		schemaOnly;
bool		dataOnly;
222
bool		aclsSkip;
223

B
Bruce Momjian 已提交
224
char		g_opaque_type[10];	/* name for the opaque type */
225 226

/* placeholders for the delimiters for comments */
227 228
char		g_comment_start[10];
char		g_comment_end[10];
229 230


B
Bruce Momjian 已提交
231 232 233 234
typedef struct _dumpContext
{
	TableInfo  *tblinfo;
	int			tblidx;
B
Bruce Momjian 已提交
235 236 237
	bool		oids;
} DumpContext;

238
static void
239
help(const char *progname)
240
{
P
Peter Eisentraut 已提交
241
	printf("%s dumps a database as a text file.\n\n", progname);
242 243 244
	puts("Usage:");
	printf("  %s [options] dbname\n\n", progname);
	puts("Options:");
B
Hi,  
Bruce Momjian 已提交
245 246

#ifdef HAVE_GETOPT_LONG
247
	puts(
B
Bruce Momjian 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
	"  -a, --data-only          dump out only the data, not the schema\n"
		 "  -b, --blobs              dump out blob data\n"
	   "  -c, --clean              clean (drop) schema prior to create\n"
		 "  -C, --create             output commands to create database\n"
		 "  -d, --inserts            dump data as INSERT, rather than COPY, commands\n"
		 "  -D, --attribute-inserts  dump data as INSERT commands with attribute names\n"
		 "  -f, --file=FILENAME      specify output file name\n"
		 "  -F, --format {c|t|p}     output file format (custom, tar, plain text)\n"
		 "  -h, --host=HOSTNAME      server host name\n"
		 "  -i, --ignore-version     proceed when database version != pg_dump version\n"
	"  -n, --no-quotes          suppress most quotes around identifiers\n"
	 "  -N, --quotes             enable most quotes around identifiers\n"
		 "  -o, --oids               dump object ids (oids)\n"
		 "  -O, --no-owner           do not output \\connect commands in plain text\n"
		 "                           format\n"
		 "  -p, --port=PORT          server port number\n"
		 "  -R, --no-reconnect       disable ALL reconnections to the database in\n"
		 "                           plain text format\n"
		 "  -s, --schema-only        dump out only the schema, no data\n"
		 "  -S, --superuser=NAME     specify the superuser user name to use in plain\n"
		 "                           text format\n"
	  "  -t, --table=TABLE        dump for this table only (* for all)\n"
270
		 "  -U, --username=NAME      connect as specified database user\n"
B
Bruce Momjian 已提交
271
		 "  -v, --verbose            verbose\n"
272
		 "  -W, --password           force password prompt (should happen automatically)\n"
B
Bruce Momjian 已提交
273 274
		 "  -x, --no-acl             do not dump ACL's (grant/revoke)\n"
		 "  -Z, --compress {0-9}     compression level for compressed formats\n"
275
		);
B
Hi,  
Bruce Momjian 已提交
276
#else
277
	puts(
B
Bruce Momjian 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
		 "  -a                       dump out only the data, no schema\n"
		 "  -b                       dump out blob data\n"
	   "  -c                       clean (drop) schema prior to create\n"
		 "  -C                       output commands to create database\n"
		 "  -d                       dump data as INSERT, rather than COPY, commands\n"
		 "  -D                       dump data as INSERT commands with attribute names\n"
		 "  -f FILENAME              specify output file name\n"
		 "  -F {c|t|p}               output file format (custom, tar, plain text)\n"
		 "  -h HOSTNAME              server host name\n"
		 "  -i                       proceed when database version != pg_dump version\n"
	"  -n                       suppress most quotes around identifiers\n"
	 "  -N                       enable most quotes around identifiers\n"
		 "  -o                       dump object ids (oids)\n"
		 "  -O                       do not output \\connect commands in plain text\n"
		 "                           format\n"
		 "  -p PORT                  server port number\n"
		 "  -R                       disable ALL reconnections to the database in\n"
		 "                           plain text format\n"
		 "  -s                       dump out only the schema, no data\n"
		 "  -S NAME                  specify the superuser user name to use in plain\n"
		 "                           text format\n"
	  "  -t TABLE                 dump for this table only (* for all)\n"
300
		 "  -U NAME                  connect as specified database user\n"
B
Bruce Momjian 已提交
301
		 "  -v                       verbose\n"
302
		 "  -W                       force password prompt (should happen automatically)\n"
B
Bruce Momjian 已提交
303 304
		 "  -x                       do not dump ACL's (grant/revoke)\n"
		 "  -Z {0-9}                 compression level for compressed formats\n"
305
		);
B
Hi,  
Bruce Momjian 已提交
306
#endif
307 308
	puts("If no database name is not supplied, then the PGDATABASE environment\nvariable value is used.\n");
	puts("Report bugs to <pgsql-bugs@postgresql.org>.");
309
}
310

311

312 313 314
static void
version(void)
{
315
	puts("pg_dump (PostgreSQL) " PG_VERSION);
316
	puts("Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group");
317
	puts("Portions Copyright (c) 1996 Regents of the University of California");
318
	puts("Read the file COPYRIGHT to see the usage and distribution terms.");
319 320
}

321

322
static void
323
exit_nicely(PGconn *conn)
324
{
325 326
	PQfinish(conn);
	exit(1);
327 328 329
}


330 331
#define COPYBUFSIZ		8192

B
Bruce Momjian 已提交
332 333 334 335 336
/*
 *	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.
 */
337

B
Bruce Momjian 已提交
338 339
static int
dumpClasses_nodumpData(Archive *fout, char *oid, void *dctxv)
340
{
B
Bruce Momjian 已提交
341 342
	const DumpContext *dctx = (DumpContext *) dctxv;
	const char *classname = dctx->tblinfo[dctx->tblidx].relname;
B
Bruce Momjian 已提交
343
	const bool	oids = dctx->oids;
344

345 346 347 348 349
	PGresult   *res;
	char		query[255];
	int			ret;
	bool		copydone;
	char		copybuf[COPYBUFSIZ];
350

B
Bruce Momjian 已提交
351 352
	if (g_verbose)
		fprintf(stderr, "%s dumping out the contents of table %s\n", g_comment_start, classname);
353

354
	if (oids == true)
355
	{
B
Bruce Momjian 已提交
356 357

		/*
358
		 * archprintf(fout, "COPY %s WITH OIDS FROM stdin;\n",
B
Bruce Momjian 已提交
359
		 * fmtId(classname, force_quotes));
360
		 *
B
Bruce Momjian 已提交
361
		 * - Not used as of V1.3 (needs to be in ArchiveEntry call)
362 363 364
		 *
		 */

365
		sprintf(query, "COPY %s WITH OIDS TO stdout;\n",
366
				fmtId(classname, force_quotes));
367 368 369
	}
	else
	{
B
Bruce Momjian 已提交
370 371 372 373

		/*
		 * archprintf(fout, "COPY %s FROM stdin;\n", fmtId(classname,
		 * force_quotes));
374 375 376 377 378
		 *
		 * - Not used as of V1.3 (needs to be in ArchiveEntry call)
		 *
		 */

379
		sprintf(query, "COPY %s TO stdout;\n", fmtId(classname, force_quotes));
380 381
	}
	res = PQexec(g_conn, query);
382 383
	if (!res ||
		PQresultStatus(res) == PGRES_FATAL_ERROR)
384
	{
385
		fprintf(stderr, "SQL query to dump the contents of Table '%s' "
386 387 388 389 390 391 392 393 394
				"did not execute.  Explanation from backend: '%s'.\n"
				"The query was: '%s'.\n",
				classname, PQerrorMessage(g_conn), query);
		exit_nicely(g_conn);
	}
	else
	{
		if (PQresultStatus(res) != PGRES_COPY_OUT)
		{
395
			fprintf(stderr, "SQL query to dump the contents of Table '%s' "
396 397 398 399 400 401 402 403 404
					"executed abnormally.\n"
					"PQexec() returned status %d when %d was expected.\n"
					"The query was: '%s'.\n",
				  classname, PQresultStatus(res), PGRES_COPY_OUT, query);
			exit_nicely(g_conn);
		}
		else
		{
			copydone = false;
405

406 407
			while (!copydone)
			{
408
				ret = PQgetline(g_conn, copybuf, COPYBUFSIZ);
409 410 411 412 413 414 415 416 417

				if (copybuf[0] == '\\' &&
					copybuf[1] == '.' &&
					copybuf[2] == '\0')
				{
					copydone = true;	/* don't print this... */
				}
				else
				{
B
Bruce Momjian 已提交
418
					archputs(copybuf, fout);
419 420
					switch (ret)
					{
421 422 423 424
						case EOF:
							copydone = true;
							/* FALLTHROUGH */
						case 0:
B
Bruce Momjian 已提交
425
							archputc('\n', fout);
426 427 428
							break;
						case 1:
							break;
429 430
					}
				}
431

B
Bruce Momjian 已提交
432
				/*
433 434
				 * THROTTLE:
				 *
B
Bruce Momjian 已提交
435 436 437 438 439
				 * 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.
440
				 *
B
Bruce Momjian 已提交
441 442 443 444 445
				 * 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:
446
				 *
B
Bruce Momjian 已提交
447 448 449
				 * 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
450 451
				 * EndIf
				 *
B
Bruce Momjian 已提交
452 453
				 * where the throttle value was the number of ms to sleep per
				 * ms of work. The calculation was done in each loop.
454
				 *
B
Bruce Momjian 已提交
455 456 457 458 459
				 * 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.
460 461 462
				 *
				 * Further discussion ensued, and the proposal was dropped.
				 *
B
Bruce Momjian 已提交
463 464 465 466 467 468
				 * 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.
469
				 *
B
Bruce Momjian 已提交
470
				 * select(0, NULL, NULL, NULL, &tvi);
471
				 *
B
Bruce Momjian 已提交
472 473 474 475
				 * This will return after the interval specified in the
				 * structure tvi. Fianally, call gettimeofday again to
				 * save the 'last sleep time'.
				 */
476
			}
B
Bruce Momjian 已提交
477
			archprintf(fout, "\\.\n");
478
		}
479
		ret = PQendcopy(g_conn);
480 481
		if (ret != 0)
		{
482
			fprintf(stderr, "SQL query to dump the contents of Table '%s' "
483 484 485 486 487
					"did not execute correctly.  After we read all the "
				 "table contents from the backend, PQendcopy() failed.  "
					"Explanation from backend: '%s'.\n"
					"The query was: '%s'.\n",
					classname, PQerrorMessage(g_conn), query);
B
Bruce Momjian 已提交
488
			PQclear(res);
489 490 491
			exit_nicely(g_conn);
		}
	}
492

B
Bruce Momjian 已提交
493
	return 1;
494 495
}

B
Bruce Momjian 已提交
496
static int
B
Bruce Momjian 已提交
497
dumpClasses_dumpData(Archive *fout, char *oid, void *dctxv)
498
{
B
Bruce Momjian 已提交
499 500
	const DumpContext *dctx = (DumpContext *) dctxv;
	const char *classname = dctx->tblinfo[dctx->tblidx].relname;
B
Bruce Momjian 已提交
501

502 503
	PGresult   *res;
	PQExpBuffer q = createPQExpBuffer();
504 505
	int			tuple;
	int			field;
506

507 508 509 510 511 512 513
	if (fout->remoteVersion >= 70100)
	{
		appendPQExpBuffer(q, "SELECT * FROM ONLY %s", fmtId(classname, force_quotes));
	} else {
		appendPQExpBuffer(q, "SELECT * FROM %s", fmtId(classname, force_quotes));
	}

B
Hi, all  
Bruce Momjian 已提交
514
	res = PQexec(g_conn, q->data);
515 516 517
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
518 519
		fprintf(stderr, "dumpClasses(): command failed.  Explanation from backend: '%s'.\n",
				PQerrorMessage(g_conn));
520 521
		exit_nicely(g_conn);
	}
522
	for (tuple = 0; tuple < PQntuples(res); tuple++)
523
	{
B
Bruce Momjian 已提交
524
		archprintf(fout, "INSERT INTO %s ", fmtId(classname, force_quotes));
525
		if (attrNames == true)
526
		{
B
Hi, all  
Bruce Momjian 已提交
527 528
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "(");
529
			for (field = 0; field < PQnfields(res); field++)
530
			{
531
				if (field > 0)
B
Hi, all  
Bruce Momjian 已提交
532 533
					appendPQExpBuffer(q, ",");
				appendPQExpBuffer(q, fmtId(PQfname(res, field), force_quotes));
534
			}
B
Hi, all  
Bruce Momjian 已提交
535
			appendPQExpBuffer(q, ") ");
B
Bruce Momjian 已提交
536
			archprintf(fout, "%s", q->data);
537
		}
B
Bruce Momjian 已提交
538
		archprintf(fout, "VALUES (");
539
		for (field = 0; field < PQnfields(res); field++)
540
		{
541
			if (field > 0)
B
Bruce Momjian 已提交
542
				archprintf(fout, ",");
543
			if (PQgetisnull(res, tuple, field))
544
			{
B
Bruce Momjian 已提交
545
				archprintf(fout, "NULL");
546 547 548
				continue;
			}
			switch (PQftype(res, field))
549
			{
550 551
				case INT2OID:
				case INT4OID:
552
				case OIDOID:	/* int types */
553
				case FLOAT4OID:
554
				case FLOAT8OID:/* float types */
555
					/* These types are printed without quotes */
B
Bruce Momjian 已提交
556
					archprintf(fout, "%s",
B
Bruce Momjian 已提交
557
							   PQgetvalue(res, tuple, field));
558
					break;
559 560 561 562 563
				case ZPBITOID:
				case VARBITOID:
					archprintf(fout, "B'%s'",
							   PQgetvalue(res, tuple, field));
					break;
564
				default:
565

566 567
					/*
					 * All other types are printed as string literals,
568
					 * with appropriate escaping of special characters.
569
					 */
570
					resetPQExpBuffer(q);
571
					formatStringLiteral(q, PQgetvalue(res, tuple, field), CONV_ALL);
572
					archprintf(fout, "%s", q->data);
573
					break;
574
			}
575
		}
B
Bruce Momjian 已提交
576
		archprintf(fout, ");\n");
577 578
	}
	PQclear(res);
B
Bruce Momjian 已提交
579
	return 1;
580 581
}

582 583 584 585 586 587 588 589
/*
 * 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
590
formatStringLiteral(PQExpBuffer buf, const char *str, const formatLiteralOptions opts)
591 592 593 594
{
	appendPQExpBufferChar(buf, '\'');
	while (*str)
	{
B
Bruce Momjian 已提交
595
		char		ch = *str++;
596 597 598

		if (ch == '\\' || ch == '\'')
		{
B
Bruce Momjian 已提交
599
			appendPQExpBufferChar(buf, ch);		/* double these */
600 601 602
			appendPQExpBufferChar(buf, ch);
		}
		else if ((unsigned char) ch < (unsigned char) ' ' &&
B
Bruce Momjian 已提交
603 604 605
				 (opts == CONV_ALL
				  || (ch != '\n' && ch != '\t')
				  ))
606
		{
B
Bruce Momjian 已提交
607 608 609 610 611

			/*
			 * generate octal escape for control chars other than
			 * whitespace
			 */
612 613 614 615 616 617 618 619 620 621 622
			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, '\'');
}

623 624
/*
 * DumpClasses -
625
 *	  dump the contents of all the classes.
626 627
 */
static void
B
Bruce Momjian 已提交
628
dumpClasses(const TableInfo *tblinfo, const int numTables, Archive *fout,
B
Bruce Momjian 已提交
629
		 const char *onlytable, const bool oids, const bool force_quotes)
630 631
{

B
Bruce Momjian 已提交
632 633 634 635 636 637 638 639 640
	int			i;
	char	   *all_only;
	DataDumperPtr dumpFn;
	DumpContext *dumpCtx;
	char	   *oidsPart;
	char		copyBuf[512];
	char	   *copyStmt;

	if (onlytable == NULL || (strlen(onlytable) == 0))
641 642
		all_only = "all";
	else
643
		all_only = "only";
644

645 646 647 648 649 650
	if (oids == true)
		oidsPart = "WITH OIDS ";
	else
		oidsPart = "";


651
	if (g_verbose)
652
		fprintf(stderr, "%s preparing to dump out the contents of %s %d table%s/sequence%s %s\n",
653
				g_comment_start, all_only,
B
Bruce Momjian 已提交
654 655 656
		 (onlytable == NULL || (strlen(onlytable) == 0)) ? numTables : 1,
			  (onlytable == NULL || (strlen(onlytable) == 0)) ? "s" : "",
			  (onlytable == NULL || (strlen(onlytable) == 0)) ? "s" : "",
657
				g_comment_end);
658

659 660
	for (i = 0; i < numTables; i++)
	{
661
		const char *classname = tblinfo[i].relname;
662 663

		/* Skip VIEW relations */
664
		if (tblinfo[i].viewdef != NULL)
665
			continue;
666 667

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

670
		if (!onlytable || (strcmp(classname, onlytable) == 0) || (strlen(onlytable) == 0))
671 672
		{
			if (g_verbose)
673
				fprintf(stderr, "%s preparing to dump out the contents of Table '%s' %s\n",
674 675
						g_comment_start, classname, g_comment_end);

B
Bruce Momjian 已提交
676 677
			/* becomeUser(fout, tblinfo[i].usename); */

B
Bruce Momjian 已提交
678 679
			dumpCtx = (DumpContext *) malloc(sizeof(DumpContext));
			dumpCtx->tblinfo = (TableInfo *) tblinfo;
B
Bruce Momjian 已提交
680 681
			dumpCtx->tblidx = i;
			dumpCtx->oids = oids;
682

B
Bruce Momjian 已提交
683
			if (!dumpData)		/* Dump/restore using COPY */
684
			{
B
Bruce Momjian 已提交
685 686
				dumpFn = dumpClasses_nodumpData;
				/* dumpClasses_nodumpData(fout, classname, oids); */
687 688 689 690
				sprintf(copyBuf, "COPY %s %s FROM stdin;\n", fmtId(tblinfo[i].relname, force_quotes),
						oidsPart);
				copyStmt = copyBuf;
			}
B
Bruce Momjian 已提交
691 692
			else
/* Restore using INSERT */
693
			{
B
Bruce Momjian 已提交
694 695
				dumpFn = dumpClasses_dumpData;
				/* dumpClasses_dumpData(fout, classname); */
696 697
				copyStmt = NULL;
			}
B
Bruce Momjian 已提交
698

P
Philip Warner 已提交
699
			ArchiveEntry(fout, tblinfo[i].oid, tblinfo[i].relname,
B
Bruce Momjian 已提交
700 701
				"TABLE DATA", NULL, "", "", copyStmt, tblinfo[i].usename,
						 dumpFn, dumpCtx);
702
		}
703
	}
704 705
}

706
int
707
main(int argc, char **argv)
708
{
B
Bruce Momjian 已提交
709 710 711
	int			c;
	const char *progname;
	const char *filename = NULL;
B
Bruce Momjian 已提交
712
	const char *format = "p";
B
Bruce Momjian 已提交
713 714 715
	const char *dbname = NULL;
	const char *pghost = NULL;
	const char *pgport = NULL;
716
	const char *username = NULL;
B
Bruce Momjian 已提交
717
	char	   *tablename = NULL;
718
	bool		oids = false;
B
Bruce Momjian 已提交
719 720
	TableInfo  *tblinfo;
	int			numTables;
721
	bool		force_password = false;
B
Bruce Momjian 已提交
722
	int			compressLevel = -1;
723
	bool		ignore_version = false;
724 725
	int			plainText = 0;
	int			outputClean = 0;
726
	int			outputCreate = 0;
727
	int			outputBlobs = 0;
728 729
	int			outputNoOwner = 0;
	int			outputNoReconnect = 0;
B
Bruce Momjian 已提交
730
	char	   *outputSuperuser = NULL;
731

B
Bruce Momjian 已提交
732
	RestoreOptions *ropt;
733

B
Hi,  
Bruce Momjian 已提交
734 735 736
#ifdef HAVE_GETOPT_LONG
	static struct option long_options[] = {
		{"data-only", no_argument, NULL, 'a'},
B
Bruce Momjian 已提交
737
		{"blobs", no_argument, NULL, 'b'},
B
Hi,  
Bruce Momjian 已提交
738
		{"clean", no_argument, NULL, 'c'},
739
		{"create", no_argument, NULL, 'C'},
B
Bruce Momjian 已提交
740 741
		{"file", required_argument, NULL, 'f'},
		{"format", required_argument, NULL, 'F'},
742
		{"inserts", no_argument, NULL, 'd'},
743
		{"attribute-inserts", no_argument, NULL, 'D'},
B
Hi,  
Bruce Momjian 已提交
744
		{"host", required_argument, NULL, 'h'},
745
		{"ignore-version", no_argument, NULL, 'i'},
746
		{"no-reconnect", no_argument, NULL, 'R'},
B
Hi,  
Bruce Momjian 已提交
747 748
		{"no-quotes", no_argument, NULL, 'n'},
		{"quotes", no_argument, NULL, 'N'},
749
		{"oids", no_argument, NULL, 'o'},
750
		{"no-owner", no_argument, NULL, 'O'},
B
Hi,  
Bruce Momjian 已提交
751 752
		{"port", required_argument, NULL, 'p'},
		{"schema-only", no_argument, NULL, 's'},
753
		{"superuser", required_argument, NULL, 'S'},
B
Hi,  
Bruce Momjian 已提交
754
		{"table", required_argument, NULL, 't'},
755 756
		{"password", no_argument, NULL, 'W'},
		{"username", required_argument, NULL, 'U'},
B
Hi,  
Bruce Momjian 已提交
757 758
		{"verbose", no_argument, NULL, 'v'},
		{"no-acl", no_argument, NULL, 'x'},
B
Bruce Momjian 已提交
759
		{"compress", required_argument, NULL, 'Z'},
B
Hi,  
Bruce Momjian 已提交
760
		{"help", no_argument, NULL, '?'},
761
		{"version", no_argument, NULL, 'V'}
762
	};
763 764
	int			optindex;

B
Hi,  
Bruce Momjian 已提交
765 766
#endif

767
	g_verbose = false;
768
	force_quotes = true;
769 770 771 772 773

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

774
	dataOnly = schemaOnly = dumpData = attrNames = false;
775

776 777 778 779
	if (!strrchr(argv[0], SEP_CHAR))
		progname = argv[0];
	else
		progname = strrchr(argv[0], SEP_CHAR) + 1;
780

781 782 783 784
	/* Set defaulty options based on progname */
	if (strcmp(progname, "pg_backup") == 0)
	{
		format = "c";
P
Philip Warner 已提交
785
		outputBlobs = true;
786
	}
787

788 789
	if (argc > 1)
	{
B
Bruce Momjian 已提交
790
		if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
791 792 793 794
		{
			help(progname);
			exit(0);
		}
B
Bruce Momjian 已提交
795
		if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
796 797 798 799 800 801
		{
			version();
			exit(0);
		}
	}

B
Hi,  
Bruce Momjian 已提交
802
#ifdef HAVE_GETOPT_LONG
803
	while ((c = getopt_long(argc, argv, "abcCdDf:F:h:inNoOp:RsS:t:uU:vWxzZ:V?", long_options, &optindex)) != -1)
B
Hi,  
Bruce Momjian 已提交
804
#else
805
	while ((c = getopt(argc, argv, "abcCdDf:F:h:inNoOp:RsS:t:uU:vWxzZ:V?-")) != -1)
B
Hi,  
Bruce Momjian 已提交
806
#endif
807

808 809 810
	{
		switch (c)
		{
811
			case 'a':			/* Dump data only */
812
				dataOnly = true;
813
				break;
814

815 816 817 818
			case 'b':			/* Dump blobs */
				outputBlobs = true;
				break;

B
Bruce Momjian 已提交
819
			case 'c':			/* clean (i.e., drop) schema prior to
B
Bruce Momjian 已提交
820
								 * create */
B
Bruce Momjian 已提交
821
				outputClean = 1;
B
Bruce Momjian 已提交
822 823
				break;

824 825 826 827 828
			case 'C':			/* Create DB */

				outputCreate = 1;
				break;

829
			case 'd':			/* dump data as proper insert strings */
830
				dumpData = true;
831
				break;
832

833 834
			case 'D':			/* dump data as proper insert strings with
								 * attr names */
835 836
				dumpData = true;
				attrNames = true;
837
				break;
838

839
			case 'f':
840 841
				filename = optarg;
				break;
842

B
Bruce Momjian 已提交
843 844 845
			case 'F':
				format = optarg;
				break;
846

B
Bruce Momjian 已提交
847
			case 'h':			/* server host */
848 849
				pghost = optarg;
				break;
850

851 852 853
			case 'i':			/* ignore database version mismatch */
				ignore_version = true;
				break;
854

B
Bruce Momjian 已提交
855 856
			case 'n':			/* Do not force double-quotes on
								 * identifiers */
857
				force_quotes = false;
858
				break;
859

860
			case 'N':			/* Force double-quotes on identifiers */
861
				force_quotes = true;
862
				break;
863

864
			case 'o':			/* Dump oids */
865
				oids = true;
866
				break;
867 868


869 870 871
			case 'O':			/* Don't reconnect to match owner */
				outputNoOwner = 1;
				break;
872

873 874 875
			case 'p':			/* server port */
				pgport = optarg;
				break;
876

877 878 879
			case 'R':			/* No reconnect */
				outputNoReconnect = 1;
				break;
880

881
			case 's':			/* dump schema only */
882
				schemaOnly = true;
883
				break;
884

B
Bruce Momjian 已提交
885 886
			case 'S':			/* Username for superuser in plain text
								 * output */
887 888
				outputSuperuser = strdup(optarg);
				break;
889

890
			case 't':			/* Dump data for this table only */
891
				{
892
					int			i;
893 894

					tablename = strdup(optarg);
B
Bruce Momjian 已提交
895 896 897 898 899

					/*
					 * quoted string? Then strip quotes and preserve
					 * case...
					 */
900 901 902
					if (tablename[0] == '"')
					{
						strcpy(tablename, &tablename[1]);
B
Bruce Momjian 已提交
903 904
						if (*(tablename + strlen(tablename) - 1) == '"')
							*(tablename + strlen(tablename) - 1) = '\0';
905 906 907 908 909
					}
					/* otherwise, convert table name to lowercase... */
					else
					{
						for (i = 0; tablename[i]; i++)
910 911
							if (isupper((unsigned char) tablename[i]))
								tablename[i] = tolower((unsigned char) tablename[i]);
912

B
Bruce Momjian 已提交
913 914 915 916 917
						/*
						 * '*' is a special case meaning ALL tables, but
						 * only if unquoted
						 */
						if (strcmp(tablename, "*") == 0)
918 919
							tablename[0] = '\0';

920
					}
921
				}
922
				break;
923

924
			case 'u':
925 926 927 928 929 930
				force_password = true;
				username = simple_prompt("Username: ", 100, true);
				break;

			case 'U':
				username = optarg;
931
				break;
932

933 934
			case 'v':			/* verbose */
				g_verbose = true;
935
				break;
936

937 938 939 940
			case 'W':
				force_password = true;
				break;

941 942
			case 'x':			/* skip ACL dump */
				aclsSkip = true;
943
				break;
944

B
Bruce Momjian 已提交
945 946 947
			case 'Z':			/* Compression Level */
				compressLevel = atoi(optarg);
				break;
948

949 950 951 952
			case 'V':
				version();
				exit(0);
				break;
953

954 955 956
#ifndef HAVE_GETOPT_LONG
			case '-':
				fprintf(stderr, "%s was compiled without support for long options.\n"
B
Bruce Momjian 已提交
957
				"Use --help for help on invocation options.\n", progname);
958 959 960
				exit(1);
				break;
#endif
961
			default:
962
				fprintf(stderr, "Try '%s --help' for more information.\n", progname);
963
				exit(1);
964 965 966
		}
	}

B
Bruce Momjian 已提交
967 968
	if (optind < (argc - 1))
	{
P
Philip Warner 已提交
969 970
		fprintf(stderr,
				"%s: extra parameters found on command line after '%s' (first is '%s').\n"
B
Bruce Momjian 已提交
971 972
				"Please respecify command.\nUse --help for help on invocation options.\n",
				progname, argv[optind], argv[optind + 1]);
P
Philip Warner 已提交
973 974 975
		exit(1);
	}

976 977 978 979 980 981 982 983 984 985 986 987 988
	/* Get the target database name */
	if (optind < argc)
		dbname = argv[optind];
	else
		dbname = getenv("PGDATABASE");
	if (!dbname)
	{
		fprintf(stderr,
				"%s: no database name specified\n",
				progname);
		exit(1);
	}

B
Bruce Momjian 已提交
989 990 991
	if (dataOnly && schemaOnly)
	{
		fprintf(stderr,
B
Bruce Momjian 已提交
992
		 "%s: 'Schema Only' and 'Data Only' are incompatible options.\n",
B
Bruce Momjian 已提交
993 994 995 996
				progname);
		exit(1);
	}

B
Bruce Momjian 已提交
997
	if (outputBlobs && tablename != NULL && strlen(tablename) > 0)
998 999
	{
		fprintf(stderr,
1000
				"%s: BLOB output is not supported for a single table. Use all tables or a full dump instead.\n",
1001 1002 1003 1004
				progname);
		exit(1);
	}

1005 1006 1007
	if (dumpData == true && oids == true)
	{
		fprintf(stderr,
1008
				"%s: INSERT's can not set oids, so INSERT and OID options can not be used together.\n",
1009
				progname);
1010
		exit(1);
1011
	}
1012

B
Bruce Momjian 已提交
1013
	if (outputBlobs == true && (format[0] == 'p' || format[0] == 'P'))
P
Philip Warner 已提交
1014 1015
	{
		fprintf(stderr,
B
Bruce Momjian 已提交
1016 1017
				"%s: BLOB output is not supported for plain text dump files. Use a different output format.\n",
				progname);
P
Philip Warner 已提交
1018 1019 1020
		exit(1);
	}

1021
	/* open the output file */
B
Bruce Momjian 已提交
1022 1023
	switch (format[0])
	{
B
Bruce Momjian 已提交
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037

		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;
1038 1039 1040 1041 1042 1043
			g_fout = CreateArchive(filename, archNull, 0);
			break;

		case 't':
		case 'T':
			g_fout = CreateArchive(filename, archTar, compressLevel);
B
Bruce Momjian 已提交
1044 1045 1046
			break;

		default:
1047
			fprintf(stderr,
B
Bruce Momjian 已提交
1048 1049
					"%s: invalid output format '%s' specified\n", progname, format);
			exit(1);
B
Bruce Momjian 已提交
1050 1051 1052 1053 1054
	}

	if (g_fout == NULL)
	{
		fprintf(stderr,
B
Bruce Momjian 已提交
1055
				"%s: could not open output file named %s for writing\n",
B
Bruce Momjian 已提交
1056 1057
				progname, filename);
		exit(1);
1058 1059
	}

1060 1061
	/* Let the archiver know how noisy to be */
	g_fout->verbose = g_verbose;
1062

B
Bruce Momjian 已提交
1063 1064
	/*
	 * Open the database using the Archiver, so it knows about it. Errors
1065
	 * mean death. Accept 7.0 & 7.1 database versions.
B
Bruce Momjian 已提交
1066
	 */
1067 1068
	g_fout->minRemoteVersion = 70000;
	g_fout->maxRemoteVersion = 70199;
1069
	g_conn = ConnectDatabase(g_fout, dbname, pghost, pgport, username, force_password, ignore_version);
1070

1071 1072 1073 1074 1075 1076 1077 1078
	/*
	 * Start serializable transaction to dump consistent data
	 */
	{
		PGresult   *res;

		res = PQexec(g_conn, "begin");
		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
B
Bruce Momjian 已提交
1079 1080
			exit_horribly(g_fout, "BEGIN command failed. Explanation from backend: '%s'.\n",
						  PQerrorMessage(g_conn));
1081

1082 1083 1084
		PQclear(res);
		res = PQexec(g_conn, "set transaction isolation level serializable");
		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
B
Bruce Momjian 已提交
1085 1086
			exit_horribly(g_fout, "SET TRANSACTION command failed. Explanation from backend: '%s'.\n",
						  PQerrorMessage(g_conn));
1087

1088 1089 1090
		PQclear(res);
	}

1091 1092 1093 1094
	if (g_fout->remoteVersion >= 70100)
		g_last_builtin_oid = findLastBuiltinOid_V71(dbname);
	else
		g_last_builtin_oid = findLastBuiltinOid_V70();
1095

1096 1097 1098 1099
	/* Dump the database definition */
	if (!dataOnly)
		dumpDatabase(g_fout);

1100
	if (oids == true)
1101
		setMaxOid(g_fout);
B
Bruce Momjian 已提交
1102 1103

	if (g_verbose)
B
Bruce Momjian 已提交
1104 1105
		fprintf(stderr, "%s last builtin oid is %u %s\n",
				g_comment_start, g_last_builtin_oid, g_comment_end);
B
Bruce Momjian 已提交
1106
	tblinfo = dumpSchema(g_fout, &numTables, tablename, aclsSkip, oids, schemaOnly, dataOnly);
1107

1108
	if (!schemaOnly)
B
Bruce Momjian 已提交
1109
		dumpClasses(tblinfo, numTables, g_fout, tablename, oids, force_quotes);
1110 1111

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

1114 1115
	if (!dataOnly)				/* dump indexes and triggers at the end
								 * for performance */
V
Vadim B. Mikheev 已提交
1116 1117
	{
		dumpTriggers(g_fout, tablename, tblinfo, numTables);
1118
		dumpRules(g_fout, tablename, tblinfo, numTables);
V
Vadim B. Mikheev 已提交
1119
	}
1120

1121 1122
	/* Now sort the output nicely */
	SortTocByOID(g_fout);
1123
	MoveToStart(g_fout, "DATABASE");
1124 1125 1126
	MoveToEnd(g_fout, "TABLE DATA");
	MoveToEnd(g_fout, "BLOBS");
	MoveToEnd(g_fout, "INDEX");
1127
	MoveToEnd(g_fout, "CONSTRAINT");
1128 1129
	MoveToEnd(g_fout, "TRIGGER");
	MoveToEnd(g_fout, "RULE");
1130
	MoveToEnd(g_fout, "SEQUENCE SET");
1131

B
Bruce Momjian 已提交
1132
	if (plainText)
B
Bruce Momjian 已提交
1133 1134
	{
		ropt = NewRestoreOptions();
B
Bruce Momjian 已提交
1135
		ropt->filename = (char *) filename;
B
Bruce Momjian 已提交
1136 1137
		ropt->dropSchema = outputClean;
		ropt->aclsSkip = aclsSkip;
1138 1139 1140 1141 1142 1143 1144 1145 1146
		ropt->superuser = outputSuperuser;
		ropt->create = outputCreate;
		ropt->noOwner = outputNoOwner;
		ropt->noReconnect = outputNoReconnect;

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

		if (compressLevel == -1)
B
Bruce Momjian 已提交
1149
			ropt->compression = 0;
B
Bruce Momjian 已提交
1150
		else
B
Bruce Momjian 已提交
1151
			ropt->compression = compressLevel;
B
Bruce Momjian 已提交
1152

1153 1154
		ropt->suppressDumpWarnings = true; /* We've already shown them */

B
Bruce Momjian 已提交
1155 1156 1157 1158
		RestoreArchive(g_fout, ropt);
	}

	CloseArchive(g_fout);
1159

1160 1161 1162
	clearTableInfo(tblinfo, numTables);
	PQfinish(g_conn);
	exit(0);
1163 1164
}

1165 1166 1167 1168 1169
/*
 * dumpDatabase:
 *	dump the database definition
 *
 */
B
Bruce Momjian 已提交
1170
static int
1171 1172
dumpDatabase(Archive *AH)
{
B
Bruce Momjian 已提交
1173 1174 1175 1176 1177 1178
	PQExpBuffer dbQry = createPQExpBuffer();
	PQExpBuffer delQry = createPQExpBuffer();
	PQExpBuffer creaQry = createPQExpBuffer();
	PGresult   *res;
	int			ntups;
	int			i_dba;
1179 1180 1181 1182 1183

	if (g_verbose)
		fprintf(stderr, "%s saving database definition\n", g_comment_start);

	/* Get the dba */
1184
	appendPQExpBuffer(dbQry, "select (select usename from pg_user where datdba = usesysid) as dba from pg_database"
B
Bruce Momjian 已提交
1185
					  " where datname = ");
1186
	formatStringLiteral(dbQry, PQdb(g_conn), CONV_ALL);
1187 1188 1189 1190 1191

	res = PQexec(g_conn, dbQry->data);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
1192 1193
		fprintf(stderr, "getDatabase(): SELECT failed.  Explanation from backend: '%s'.\n",
				PQerrorMessage(g_conn));
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	if (ntups != 1)
	{
		fprintf(stderr, "getDatabase(): SELECT returned %d databases.\n", ntups);
		exit_nicely(g_conn);
	}

	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 已提交
1209 1210 1211 1212
	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 */ );
1213 1214 1215 1216 1217 1218 1219

	PQclear(res);

	return 1;
}


1220 1221 1222 1223 1224 1225
/*
 * dumpBlobs:
 *	dump all blobs
 *
 */

B
Bruce Momjian 已提交
1226
#define loBufSize 16384
1227 1228
#define loFetchSize 1000

B
Bruce Momjian 已提交
1229 1230
static int
dumpBlobs(Archive *AH, char *junkOid, void *junkVal)
1231
{
B
Bruce Momjian 已提交
1232 1233 1234 1235 1236 1237 1238 1239
	PQExpBuffer oidQry = createPQExpBuffer();
	PQExpBuffer oidFetchQry = createPQExpBuffer();
	PGresult   *res;
	int			i;
	int			loFd;
	char		buf[loBufSize];
	int			cnt;
	int			blobOid;
1240 1241 1242 1243 1244

	if (g_verbose)
		fprintf(stderr, "%s saving BLOBs\n", g_comment_start);

	/* Cursor to get all BLOB tables */
1245 1246 1247 1248 1249 1250
	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'");
	}
1251 1252 1253 1254

	res = PQexec(g_conn, oidQry->data);
	if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
	{
B
Bruce Momjian 已提交
1255 1256
		fprintf(stderr, "dumpBlobs(): Declare Cursor failed.  Explanation from backend: '%s'.\n",
				PQerrorMessage(g_conn));
1257 1258 1259 1260 1261 1262
		exit_nicely(g_conn);
	}

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

B
Bruce Momjian 已提交
1263 1264
	do
	{
1265 1266 1267 1268 1269 1270
		/* Do a fetch */
		PQclear(res);
		res = PQexec(g_conn, oidFetchQry->data);

		if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
		{
B
Bruce Momjian 已提交
1271 1272
			fprintf(stderr, "dumpBlobs(): Fetch Cursor failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
			exit_nicely(g_conn);
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
		}

		/* Process the tuples, if any */
		for (i = 0; i < PQntuples(res); i++)
		{
			blobOid = atoi(PQgetvalue(res, i, 0));
			/* Open the BLOB */
			loFd = lo_open(g_conn, blobOid, INV_READ);
			if (loFd == -1)
			{
				fprintf(stderr, "dumpBlobs(): Could not open large object.  "
B
Bruce Momjian 已提交
1284
						"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1285 1286 1287 1288 1289 1290
				exit_nicely(g_conn);
			}

			StartBlob(AH, blobOid);

			/* Now read it in chunks, sending data to archive */
B
Bruce Momjian 已提交
1291 1292
			do
			{
1293
				cnt = lo_read(g_conn, loFd, buf, loBufSize);
B
Bruce Momjian 已提交
1294 1295
				if (cnt < 0)
				{
1296
					fprintf(stderr, "dumpBlobs(): Error reading large object. "
B
Bruce Momjian 已提交
1297
							" Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1298 1299 1300
					exit_nicely(g_conn);
				}

B
Bruce Momjian 已提交
1301
				WriteData(AH, buf, cnt);
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314

			} while (cnt > 0);

			lo_close(g_conn, loFd);

			EndBlob(AH, blobOid);

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

	return 1;
}

1315
/*
1316 1317
 * getTypes:
 *	  read all base types in the system catalogs and return them in the
1318 1319
 * TypeInfo* structure
 *
1320
 *	numTypes is set to the number of types read in
1321 1322
 *
 */
1323
TypeInfo   *
1324 1325
getTypes(int *numTypes)
{
B
Bruce Momjian 已提交
1326
	PGresult   *res;
1327 1328
	int			ntups;
	int			i;
1329
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
1330
	TypeInfo   *tinfo;
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346

	int			i_oid;
	int			i_typowner;
	int			i_typname;
	int			i_typlen;
	int			i_typprtlen;
	int			i_typinput;
	int			i_typoutput;
	int			i_typreceive;
	int			i_typsend;
	int			i_typelem;
	int			i_typdelim;
	int			i_typdefault;
	int			i_typrelid;
	int			i_typbyval;
	int			i_usename;
1347
	int			i_typedefn;
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359

	/* find all base types */

	/*
	 * we include even the built-in types because those may be used as
	 * array elements by user-defined types
	 */

	/*
	 * we filter out the built-in types when we dump out the types
	 */

1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
	if (g_fout->remoteVersion < 70100)
	{
		appendPQExpBuffer(query, "SELECT pg_type.oid, typowner, typname, typlen, typprtlen, "
						"typinput, typoutput, typreceive, typsend, typelem, typdelim, "
						"typdefault, typrelid, typbyval, "
						"(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, "
						"typdefault, typrelid, typbyval, "
						"(select usename from pg_user where typowner = usesysid) as usename, "
						"format_type(pg_type.oid, NULL) as typedefn "
						"from pg_type");
	}
1376

B
Hi, all  
Bruce Momjian 已提交
1377
	res = PQexec(g_conn, query->data);
1378 1379 1380
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
1381
		fprintf(stderr, "getTypes(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

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

	i_oid = PQfnumber(res, "oid");
	i_typowner = PQfnumber(res, "typowner");
	i_typname = PQfnumber(res, "typname");
	i_typlen = PQfnumber(res, "typlen");
	i_typprtlen = PQfnumber(res, "typprtlen");
	i_typinput = PQfnumber(res, "typinput");
	i_typoutput = PQfnumber(res, "typoutput");
	i_typreceive = PQfnumber(res, "typreceive");
	i_typsend = PQfnumber(res, "typsend");
	i_typelem = PQfnumber(res, "typelem");
	i_typdelim = PQfnumber(res, "typdelim");
	i_typdefault = PQfnumber(res, "typdefault");
	i_typrelid = PQfnumber(res, "typrelid");
	i_typbyval = PQfnumber(res, "typbyval");
	i_usename = PQfnumber(res, "usename");
1404
	i_typedefn = PQfnumber(res, "typedefn");
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421

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

1424
		if (strlen(tinfo[i].usename) == 0)
B
Bruce Momjian 已提交
1425
			fprintf(stderr, "WARNING: owner of type '%s' appears to be invalid\n", tinfo[i].typname);
1426

1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
		if (strcmp(PQgetvalue(res, i, i_typbyval), "f") == 0)
			tinfo[i].passedbyvalue = 0;
		else
			tinfo[i].passedbyvalue = 1;

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

	*numTypes = ntups;

	PQclear(res);

	return tinfo;
1447 1448 1449 1450
}

/*
 * getOperators:
1451
 *	  read all operators in the system catalogs and return them in the
1452 1453
 * OprInfo* structure
 *
1454 1455
 *	numOprs is set to the number of operators read in
 *
1456 1457
 *
 */
1458
OprInfo    *
1459 1460
getOperators(int *numOprs)
{
1461
	PGresult   *res;
1462 1463
	int			ntups;
	int			i;
1464
	PQExpBuffer query = createPQExpBuffer();
1465

B
Bruce Momjian 已提交
1466
	OprInfo    *oprinfo;
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481

	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;
1482 1483 1484 1485 1486 1487

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

B
Hi, all  
Bruce Momjian 已提交
1488
	appendPQExpBuffer(query, "SELECT pg_operator.oid, oprname, oprkind, oprcode, "
1489
			   "oprleft, oprright, oprcom, oprnegate, oprrest, oprjoin, "
B
Bruce Momjian 已提交
1490 1491 1492
					  "oprcanhash, oprlsortop, oprrsortop, "
	"(select usename from pg_user where oprowner = usesysid) as usename "
					  "from pg_operator");
1493

B
Hi, all  
Bruce Momjian 已提交
1494
	res = PQexec(g_conn, query->data);
1495 1496 1497
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
1498
		fprintf(stderr, "getOperators(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
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 1532 1533 1534 1535 1536 1537
		exit_nicely(g_conn);
	}

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

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

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

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

		if (strlen(oprinfo[i].usename) == 0)
			fprintf(stderr, "WARNING: owner of operator '%s' appears to be invalid\n",
B
Bruce Momjian 已提交
1541
					oprinfo[i].oprname);
1542

1543 1544 1545 1546 1547
	}

	PQclear(res);

	return oprinfo;
1548 1549
}

1550
void
1551
clearTypeInfo(TypeInfo *tp, int numTypes)
1552
{
1553
	int			i;
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 1579 1580 1581 1582 1583 1584 1585 1586

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

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

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

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

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

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

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

		if (tblinfo[i].sequence)
			continue;

		/* Process Attributes */
		for (j = 0; j < tblinfo[i].numatts; j++)
		{
B
Bruce,  
Bruce Momjian 已提交
1643 1644
			if (tblinfo[i].attoids[j])
				free(tblinfo[i].attoids[j]);
1645 1646 1647 1648 1649
			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 numIndices)
1749
{
1750 1751
	int			i,
				a;
1752 1753 1754 1755 1756

	if (!ind)
		return;
	for (i = 0; i < numIndices; ++i)
	{
B
Bruce,  
Bruce Momjian 已提交
1757 1758
		if (ind[i].indoid)
			free(ind[i].indoid);
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
		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);
1769 1770
		if (ind[i].indisprimary)
			free(ind[i].indisprimary);
1771 1772 1773 1774 1775 1776 1777 1778 1779
		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);
1780 1781 1782
}

void
B
Bruce Momjian 已提交
1783
clearAggInfo(AggInfo *agginfo, int numArgs)
1784
{
1785
	int			i;
1786 1787 1788 1789 1790 1791 1792 1793 1794

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

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

	int			i_oid;
	int			i_aggname;
1831
	int			i_aggtransfn;
1832
	int			i_aggfinalfn;
1833
	int			i_aggtranstype;
1834
	int			i_aggbasetype;
1835
	int			i_agginitval;
1836
	int			i_usename;
1837
	int			i_convertok;
1838 1839 1840

	/* find all user-defined aggregates */

1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
	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");
	}
1857

B
Hi, all  
Bruce Momjian 已提交
1858
	res = PQexec(g_conn, query->data);
1859 1860 1861
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
1862
		fprintf(stderr, "getAggregates(): SELECT failed.  Explanation from backend: '%s'.\n",
B
Bruce Momjian 已提交
1863
				PQerrorMessage(g_conn));
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
		exit_nicely(g_conn);
	}

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

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

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

	for (i = 0; i < ntups; i++)
	{
		agginfo[i].oid = strdup(PQgetvalue(res, i, i_oid));
		agginfo[i].aggname = strdup(PQgetvalue(res, i, i_aggname));
1886
		agginfo[i].aggtransfn = strdup(PQgetvalue(res, i, i_aggtransfn));
1887
		agginfo[i].aggfinalfn = strdup(PQgetvalue(res, i, i_aggfinalfn));
1888
		agginfo[i].aggtranstype = strdup(PQgetvalue(res, i, i_aggtranstype));
1889
		agginfo[i].aggbasetype = strdup(PQgetvalue(res, i, i_aggbasetype));
1890
		agginfo[i].agginitval = strdup(PQgetvalue(res, i, i_agginitval));
1891
		agginfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1892 1893
		if (strlen(agginfo[i].usename) == 0)
			fprintf(stderr, "WARNING: owner of aggregate '%s' appears to be invalid\n",
B
Bruce Momjian 已提交
1894
					agginfo[i].aggname);
1895

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

1898 1899 1900 1901 1902
	}

	PQclear(res);

	return agginfo;
1903 1904 1905 1906
}

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

	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;
1932
	int			i_iscachable;
1933
	int			i_isstrict;
1934
	int			i_usename;
1935 1936 1937

	/* find all user-defined funcs */

1938 1939 1940 1941 1942 1943
	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, "
1944
				"proiscachable, 'f'::boolean as proisstrict "
1945 1946 1947 1948 1949
				"from pg_proc "
				"where pg_proc.oid > '%u'::oid",
					  g_last_builtin_oid);
	} else {
		appendPQExpBuffer(query,
1950
		   "SELECT pg_proc.oid, proname, prolang, pronargs, prorettype, "
1951
					  "proretset, proargtypes, prosrc, probin, "
1952 1953 1954 1955
				"(select usename from pg_user where proowner = usesysid) as usename, "
				"proiscachable, proisstrict "
				"from pg_proc "
				"where pg_proc.oid > '%u'::oid",
1956
					  g_last_builtin_oid);
1957
	}
1958

B
Hi, all  
Bruce Momjian 已提交
1959
	res = PQexec(g_conn, query->data);
1960 1961 1962
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
1963 1964
		fprintf(stderr, "getFuncs(): SELECT failed.  Explanation from backend: '%s'.\n",
				PQerrorMessage(g_conn));
1965 1966 1967 1968 1969 1970 1971 1972 1973
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numFuncs = ntups;

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

1974 1975
	memset((char *) finfo, 0, ntups * sizeof(FuncInfo));

1976 1977 1978 1979 1980 1981 1982 1983 1984
	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");
1985
	i_iscachable = PQfnumber(res, "proiscachable");
1986
	i_isstrict = PQfnumber(res, "proisstrict");
1987 1988 1989 1990 1991 1992 1993
	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));

1994
		finfo[i].prosrc = strdup(PQgetvalue(res, i, i_prosrc));
1995 1996 1997 1998 1999
		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));
2000
		finfo[i].lang = atoi(PQgetvalue(res, i, i_prolang));
2001
		finfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
B
Bruce Momjian 已提交
2002 2003
		finfo[i].iscachable = (strcmp(PQgetvalue(res, i, i_iscachable), "t") == 0);
		finfo[i].isstrict = (strcmp(PQgetvalue(res, i, i_isstrict), "t") == 0);
2004 2005 2006

		if (strlen(finfo[i].usename) == 0)
			fprintf(stderr, "WARNING: owner of function '%s' appears to be invalid\n",
B
Bruce Momjian 已提交
2007
					finfo[i].proname);
2008

2009 2010
		if (finfo[i].nargs < 0 || finfo[i].nargs > FUNC_MAX_ARGS)
		{
2011
			fprintf(stderr, "getFuncs(): failed sanity check: %s has %d args\n",
2012
					finfo[i].proname, finfo[i].nargs);
2013
			exit(1);
2014 2015 2016 2017
		}
		parseNumericArray(PQgetvalue(res, i, i_proargtypes),
						  finfo[i].argtypes,
						  finfo[i].nargs);
2018 2019 2020 2021 2022 2023
		finfo[i].dumped = 0;
	}

	PQclear(res);

	return finfo;
2024 2025 2026 2027 2028

}

/*
 * getTables
2029
 *	  read all the user-defined tables (no indices, no catalogs)
2030 2031
 * in the system catalogs return them in the TableInfo* structure
 *
2032 2033
 * numTables is set to the number of tables read in
 *
2034 2035
 *
 */
2036
TableInfo  *
V
Vadim B. Mikheev 已提交
2037
getTables(int *numTables, FuncInfo *finfo, int numFuncs)
2038
{
2039
	PGresult   *res;
2040 2041
	int			ntups;
	int			i;
2042
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
2043
	PQExpBuffer delqry = createPQExpBuffer();
2044
	TableInfo  *tblinfo;
2045

B
Bruce Momjian 已提交
2046
	int			i_reloid;
2047 2048 2049 2050
	int			i_relname;
	int			i_relkind;
	int			i_relacl;
	int			i_usename;
V
Vadim B. Mikheev 已提交
2051 2052
	int			i_relchecks;
	int			i_reltriggers;
2053
	int			i_relhasindex;
2054 2055 2056 2057 2058

	char		relkindview[2];

	relkindview[0] = RELKIND_VIEW;
	relkindview[1] = '\0';
2059 2060 2061 2062 2063 2064

	/*
	 * find all the user-defined tables (no indices and no catalogs),
	 * ordering by oid is important so that we always process the parent
	 * tables before the child tables when traversing the tblinfo*
	 *
2065
	 * we ignore tables that are not type 'r' (ordinary relation) or 'S'
2066
	 * (sequence) or 'v' (view).
2067 2068
	 */

2069 2070 2071
	if (g_fout->remoteVersion >= 70100)
	{
		appendPQExpBuffer(query,
2072
					  "SELECT pg_class.oid, relname, relacl, relkind, "
2073
					  "(select usename from pg_user where relowner = usesysid) as usename, "
2074
					  "relchecks, reltriggers, relhasindex "
2075 2076
					  "from pg_class "
					  "where relname !~ '^pg_' "
2077 2078
					  "and relkind in ('%c', '%c', '%c') "
					  "order by oid",
B
Bruce Momjian 已提交
2079
					  RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2080 2081
	} else {
		/* 
2082 2083
		 * 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.
2084 2085 2086 2087
		 */
		appendPQExpBuffer(query,
					  "SELECT c.oid, relname, relacl, "
					  "CASE WHEN relhasrules and relkind = 'r' "
2088 2089 2090 2091 2092
					  "  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, "
2093 2094 2095 2096 2097
					  "relchecks, reltriggers, relhasindex "
					  "from pg_class c "
					  "where relname !~ '^pg_' "
					  "and relkind in ('%c', '%c', '%c') "
					  "order by oid",
2098
					  RELKIND_VIEW,
2099 2100
					  RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
	}
2101

B
Hi, all  
Bruce Momjian 已提交
2102
	res = PQexec(g_conn, query->data);
2103 2104 2105
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
2106 2107
		fprintf(stderr, "getTables(): SELECT failed.  Explanation from backend: '%s'.\n",
				PQerrorMessage(g_conn));
2108 2109 2110 2111 2112 2113 2114 2115 2116
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numTables = ntups;

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

B
Bruce Momjian 已提交
2117
	i_reloid = PQfnumber(res, "oid");
2118 2119
	i_relname = PQfnumber(res, "relname");
	i_relacl = PQfnumber(res, "relacl");
2120
	i_relkind = PQfnumber(res, "relkind");
2121
	i_usename = PQfnumber(res, "usename");
V
Vadim B. Mikheev 已提交
2122 2123
	i_relchecks = PQfnumber(res, "relchecks");
	i_reltriggers = PQfnumber(res, "reltriggers");
B
Hi, all  
Bruce Momjian 已提交
2124
	i_relhasindex = PQfnumber(res, "relhasindex");
2125 2126 2127

	for (i = 0; i < ntups; i++)
	{
B
Bruce Momjian 已提交
2128
		tblinfo[i].oid = strdup(PQgetvalue(res, i, i_reloid));
2129 2130 2131 2132
		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 已提交
2133 2134
		tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
		tblinfo[i].ntrig = atoi(PQgetvalue(res, i, i_reltriggers));
2135

2136 2137
		if (strlen(tblinfo[i].usename) == 0)
			fprintf(stderr, "WARNING: owner of table '%s' appears to be invalid\n",
B
Bruce Momjian 已提交
2138
					tblinfo[i].relname);
2139

2140 2141 2142 2143 2144 2145
		/* Get view definition */
		if (strcmp(PQgetvalue(res, i, i_relkind), relkindview) == 0)
		{
			PGresult   *res2;

			resetPQExpBuffer(query);
2146 2147
			appendPQExpBuffer(query, "SELECT definition as viewdef, ");
			/* XXX 7.2 - replace with att from pg_views or some other generic source */
2148 2149 2150
			appendPQExpBuffer(query, "(select oid from pg_rewrite where "
										" rulename=('_RET' || viewname)::name) as view_oid"
										" from pg_views where viewname = ");
2151
			formatStringLiteral(query, tblinfo[i].relname, CONV_ALL);
2152 2153
			appendPQExpBuffer(query, ";");

2154 2155 2156 2157
			res2 = PQexec(g_conn, query->data);
			if (!res2 || PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
				fprintf(stderr, "getTables(): SELECT (for VIEW DEFINITION) failed.  "
B
Bruce Momjian 已提交
2158 2159
						"Explanation from backend: %s",
						PQerrorMessage(g_conn));
2160 2161 2162
				exit_nicely(g_conn);
			}

B
Bruce Momjian 已提交
2163
			if (PQntuples(res2) != 1)
2164 2165 2166
			{
				if (PQntuples(res2) < 1)
				{
2167
					fprintf(stderr, "getTables(): SELECT (for VIEW %s) returned no definitions\n",
B
Bruce Momjian 已提交
2168 2169 2170 2171
							tblinfo[i].relname);
				}
				else
				{
2172
					fprintf(stderr, "getTables(): SELECT (for VIEW %s) returned more than 1 definition\n",
B
Bruce Momjian 已提交
2173
							tblinfo[i].relname);
2174 2175 2176 2177
				}
				exit_nicely(g_conn);
			}

2178 2179 2180 2181 2182 2183 2184
			if (PQgetisnull(res2, 0, 1))
			{
				fprintf(stderr, "getTables(): SELECT (for VIEW %s) returned NULL oid\n", tblinfo[i].relname);
				fprintf(stderr, "SELECT was: %s\n", query->data);
				exit_nicely(g_conn);
			}

2185
			tblinfo[i].viewdef = strdup(PQgetvalue(res2, 0, 0));
2186
			tblinfo[i].viewoid = strdup(PQgetvalue(res2, 0, 1));
2187

B
Bruce Momjian 已提交
2188
			if (strlen(tblinfo[i].viewdef) == 0)
2189 2190
			{
				fprintf(stderr, "getTables(): SELECT (for VIEW %s) returned empty definition",
B
Bruce Momjian 已提交
2191
						tblinfo[i].relname);
2192 2193 2194 2195 2196 2197
				exit_nicely(g_conn);
			}
		}
		else
			tblinfo[i].viewdef = NULL;

2198 2199 2200
		/* 
		 * Get non-inherited CHECK constraints, if any.
		 *
B
Bruce Momjian 已提交
2201 2202
		 * Exclude inherited CHECKs from CHECK constraints total. If a
		 * constraint matches by name and condition with a constraint
2203 2204
		 * belonging to a parent class (OR conditions match and both
	     * names start with '$', we assume it was inherited.
2205 2206
		 */
		if (tblinfo[i].ncheck > 0)
V
Vadim B. Mikheev 已提交
2207 2208
		{
			PGresult   *res2;
2209 2210
			int			i_rcname,
						i_rcsrc;
V
Vadim B. Mikheev 已提交
2211 2212
			int			ntups2;
			int			i2;
2213

V
Vadim B. Mikheev 已提交
2214
			if (g_verbose)
2215
				fprintf(stderr, "%s finding CHECK constraints for relation: '%s' %s\n",
V
Vadim B. Mikheev 已提交
2216 2217 2218
						g_comment_start,
						tblinfo[i].relname,
						g_comment_end);
2219

B
Hi, all  
Bruce Momjian 已提交
2220 2221
			resetPQExpBuffer(query);
			appendPQExpBuffer(query, "SELECT rcname, rcsrc from pg_relcheck "
2222
							  " where rcrelid = '%s'::oid "
2223
							  "   and not exists "
2224 2225 2226 2227 2228 2229 2230 2231
							  "  (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) "
2232
							  " Order By oid ",
2233
							  tblinfo[i].oid);
B
Hi, all  
Bruce Momjian 已提交
2234
			res2 = PQexec(g_conn, query->data);
V
Vadim B. Mikheev 已提交
2235
			if (!res2 ||
2236
				PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
2237
			{
B
Bruce Momjian 已提交
2238 2239
				fprintf(stderr, "getTables(): SELECT (for CHECK) failed.  "
						"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
V
Vadim B. Mikheev 已提交
2240 2241 2242
				exit_nicely(g_conn);
			}
			ntups2 = PQntuples(res2);
2243
			if (ntups2 > tblinfo[i].ncheck)
V
Vadim B. Mikheev 已提交
2244
			{
2245 2246
				fprintf(stderr, "getTables(): relation '%s': a maximum of %d CHECKs "
									"were expected, but got %d\n",
2247
						tblinfo[i].relname, tblinfo[i].ncheck, ntups2);
V
Vadim B. Mikheev 已提交
2248 2249
				exit_nicely(g_conn);
			}
2250 2251 2252 2253

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

V
Vadim B. Mikheev 已提交
2254 2255
			i_rcname = PQfnumber(res2, "rcname");
			i_rcsrc = PQfnumber(res2, "rcsrc");
2256
			tblinfo[i].check_expr = (char **) malloc(ntups2 * sizeof(char *));
V
Vadim B. Mikheev 已提交
2257 2258
			for (i2 = 0; i2 < ntups2; i2++)
			{
B
Bruce Momjian 已提交
2259 2260
				const char *name = PQgetvalue(res2, i2, i_rcname);
				const char *expr = PQgetvalue(res2, i2, i_rcsrc);
2261

B
Hi, all  
Bruce Momjian 已提交
2262
				resetPQExpBuffer(query);
2263 2264
				if (name[0] != '$')
				{
2265 2266
					appendPQExpBuffer(query, "CONSTRAINT %s ",
									  fmtId(name, force_quotes));
B
Bruce Momjian 已提交
2267
				}
2268
				appendPQExpBuffer(query, "CHECK (%s)", expr);
B
Hi, all  
Bruce Momjian 已提交
2269
				tblinfo[i].check_expr[i2] = strdup(query->data);
V
Vadim B. Mikheev 已提交
2270 2271 2272 2273 2274
			}
			PQclear(res2);
		}
		else
			tblinfo[i].check_expr = NULL;
2275

2276 2277
		/* Get primary key */
		if (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0)
2278
		{
2279
			PGresult   *res2;
B
Bruce Momjian 已提交
2280

B
Hi, all  
Bruce Momjian 已提交
2281
			resetPQExpBuffer(query);
B
Bruce Momjian 已提交
2282
			appendPQExpBuffer(query,
2283
							  "SELECT Oid FROM pg_index i WHERE i.indisprimary AND i.indrelid = %s ",
2284
							  tblinfo[i].oid);
2285
			res2 = PQexec(g_conn, query->data);
B
Bruce Momjian 已提交
2286 2287
			if (!res2 || PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
2288 2289
				fprintf(stderr, "getTables(): SELECT (for PRIMARY KEY) failed on table %s.  Explanation from backend: %s\n",
						tblinfo[i].relname, PQerrorMessage(g_conn));
B
Bruce Momjian 已提交
2290 2291
				exit_nicely(g_conn);
			}
2292

B
Bruce Momjian 已提交
2293 2294
			if (PQntuples(res2) > 1)
			{
2295 2296
				fprintf(stderr, "getTables(): SELECT (for PRIMARY KEY) produced more than one row on table %s.\n",
						tblinfo[i].relname);
2297
				exit_nicely(g_conn);
2298 2299
			}

B
Bruce Momjian 已提交
2300
			if (PQntuples(res2) == 1)
2301
				tblinfo[i].pkIndexOid = strdup(PQgetvalue(res2, 0, 0));
B
Bruce Momjian 已提交
2302
			else
2303 2304
				tblinfo[i].pkIndexOid = NULL;

2305
		}
2306
		else
2307
			tblinfo[i].pkIndexOid = NULL;
B
Bruce Momjian 已提交
2308

2309
		/* Get primary key name (if primary key exist) */
2310
		if (tblinfo[i].pkIndexOid != NULL)
2311 2312
		{
			PGresult   *res2;
B
Bruce Momjian 已提交
2313
			int			n;
2314 2315

			resetPQExpBuffer(query);
2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334
			if (g_fout->remoteVersion < 70100) 
			{
				/* Fake the LOJ from below */
				appendPQExpBuffer(query,
							  "  SELECT c.relname "
							  "    FROM pg_index i, pg_class c "
							  "    WHERE     i.indrelid = %s"
							  "        AND   i.indisprimary "
							  "        AND   c.oid = i.indexrelid"
							  " UNION ALL "
							  "  SELECT NULL "
							  "    FROM pg_index i "
							  "    WHERE i.indrelid = %s"
							  "    AND   i.indisprimary "
							  "    And NOT Exists(Select * From pg_class c Where c.oid = i.indexrelid)",
							  tblinfo[i].oid, tblinfo[i].oid);

			} else {
				appendPQExpBuffer(query,
2335
							  "SELECT c.relname "
2336
							  "FROM pg_index i LEFT OUTER JOIN pg_class c ON c.oid = i.indexrelid "
2337
							  "WHERE i.indrelid = %s"
2338
							  "AND   i.indisprimary ",
2339
							  tblinfo[i].oid);
2340 2341
			}

2342 2343 2344
			res2 = PQexec(g_conn, query->data);
			if (!res2 || PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
2345 2346
				fprintf(stderr, "getTables(): SELECT (for PRIMARY KEY NAME) failed for table %s.  Explanation from backend: %s",
						tblinfo[i].relname, PQerrorMessage(g_conn));
2347 2348 2349 2350 2351 2352 2353
				exit_nicely(g_conn);
			}

			n = PQntuples(res2);
			if (n != 1)
			{
				fprintf(stderr,
2354
						"getTables(): SELECT (for PRIMARY KEY NAME) failed for table %s. "
B
Bruce Momjian 已提交
2355
						"This is impossible but object with OID == %s have %d primary keys.\n",
2356
						tblinfo[i].relname,
2357 2358 2359 2360 2361
						tblinfo[i].oid,
						n);
				exit_nicely(g_conn);
			}

2362 2363 2364
			/* Sanity check on LOJ */
			if (PQgetisnull(res2, 0, 0))
			{
B
Bruce Momjian 已提交
2365
				fprintf(stderr, "getTables(): SELECT (for PRIMARY KEY NAME) on table %s returned NULL value.\n",
2366 2367 2368 2369
						tblinfo[i].relname);
				exit_nicely(g_conn);
			}

2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
			tblinfo[i].primary_key_name =
				strdup(fmtId(PQgetvalue(res2, 0, 0), force_quotes));
			if (tblinfo[i].primary_key_name == NULL)
			{
				perror("strdup");
				exit(1);
			}
		}
		else
			tblinfo[i].primary_key_name = NULL;

V
Vadim B. Mikheev 已提交
2381 2382 2383 2384
		/* Get Triggers */
		if (tblinfo[i].ntrig > 0)
		{
			PGresult   *res2;
B
Bruce,  
Bruce Momjian 已提交
2385
			int			i_tgoid,
2386
						i_tgname,
2387 2388 2389
						i_tgfoid,
						i_tgtype,
						i_tgnargs,
2390 2391 2392 2393
						i_tgargs,
						i_tgisconstraint,
						i_tgconstrname,
						i_tgdeferrable,
2394 2395
						i_tgconstrrelid,
						i_tgconstrrelname,
2396
						i_tginitdeferred;
V
Vadim B. Mikheev 已提交
2397 2398
			int			ntups2;
			int			i2;
2399

V
Vadim B. Mikheev 已提交
2400
			if (g_verbose)
2401
				fprintf(stderr, "%s finding Triggers for relation: '%s' %s\n",
V
Vadim B. Mikheev 已提交
2402 2403 2404
						g_comment_start,
						tblinfo[i].relname,
						g_comment_end);
2405

B
Hi, all  
Bruce Momjian 已提交
2406
			resetPQExpBuffer(query);
2407 2408 2409 2410 2411 2412
			appendPQExpBuffer(query, 
								"SELECT tgname, tgfoid, tgtype, tgnargs, tgargs, "
								"tgisconstraint, tgconstrname, tgdeferrable, "
								"tgconstrrelid, tginitdeferred, oid, "
								"(select relname from pg_class where oid = tgconstrrelid) "
								"		as tgconstrrelname "
2413 2414 2415
							  "from pg_trigger "
							  "where tgrelid = '%s'::oid ",
							  tblinfo[i].oid);
B
Hi, all  
Bruce Momjian 已提交
2416
			res2 = PQexec(g_conn, query->data);
V
Vadim B. Mikheev 已提交
2417
			if (!res2 ||
2418
				PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
2419
			{
B
Bruce Momjian 已提交
2420
				fprintf(stderr, "getTables(): SELECT (for TRIGGER) failed.  "
B
Bruce Momjian 已提交
2421
						"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
V
Vadim B. Mikheev 已提交
2422 2423 2424 2425 2426
				exit_nicely(g_conn);
			}
			ntups2 = PQntuples(res2);
			if (ntups2 != tblinfo[i].ntrig)
			{
2427
				fprintf(stderr, "getTables(): relation '%s': %d Triggers were expected, but got %d\n",
2428
						tblinfo[i].relname, tblinfo[i].ntrig, ntups2);
V
Vadim B. Mikheev 已提交
2429 2430 2431 2432 2433 2434 2435
				exit_nicely(g_conn);
			}
			i_tgname = PQfnumber(res2, "tgname");
			i_tgfoid = PQfnumber(res2, "tgfoid");
			i_tgtype = PQfnumber(res2, "tgtype");
			i_tgnargs = PQfnumber(res2, "tgnargs");
			i_tgargs = PQfnumber(res2, "tgargs");
B
Bruce,  
Bruce Momjian 已提交
2436
			i_tgoid = PQfnumber(res2, "oid");
2437 2438 2439
			i_tgisconstraint = PQfnumber(res2, "tgisconstraint");
			i_tgconstrname = PQfnumber(res2, "tgconstrname");
			i_tgdeferrable = PQfnumber(res2, "tgdeferrable");
2440 2441
			i_tgconstrrelid = PQfnumber(res2, "tgconstrrelid");
			i_tgconstrrelname = PQfnumber(res2, "tgconstrrelname");
2442 2443
			i_tginitdeferred = PQfnumber(res2, "tginitdeferred");

B
Bruce Momjian 已提交
2444
			tblinfo[i].triggers = (TrigInfo *) malloc(ntups2 * sizeof(TrigInfo));
B
Hi, all  
Bruce Momjian 已提交
2445 2446
			resetPQExpBuffer(query);
			for (i2 = 0; i2 < ntups2; i2++)
V
Vadim B. Mikheev 已提交
2447
			{
2448
				const char *tgfuncoid = PQgetvalue(res2, i2, i_tgfoid);
2449
				char	   *tgfunc = NULL;
2450 2451
				int2		tgtype = atoi(PQgetvalue(res2, i2, i_tgtype));
				int			tgnargs = atoi(PQgetvalue(res2, i2, i_tgnargs));
B
Bruce Momjian 已提交
2452
				const char *tgargs = PQgetvalue(res2, i2, i_tgargs);
2453 2454 2455
				int			tgisconstraint;
				int			tgdeferrable;
				int			tginitdeferred;
2456 2457
				char	   *tgconstrrelid;
				char	   *tgname;
B
Bruce Momjian 已提交
2458
				const char *p;
2459 2460
				int			findx;

2461 2462
				tgname = PQgetvalue(res2, i2, i_tgname);

2463
				if (strcmp(PQgetvalue(res2, i2, i_tgisconstraint), "f") == 0)
2464
					tgisconstraint = 0;
2465
				else
2466
					tgisconstraint = 1;
2467 2468

				if (strcmp(PQgetvalue(res2, i2, i_tgdeferrable), "f") == 0)
2469
					tgdeferrable = 0;
2470
				else
2471
					tgdeferrable = 1;
2472 2473

				if (strcmp(PQgetvalue(res2, i2, i_tginitdeferred), "f") == 0)
2474
					tginitdeferred = 0;
2475
				else
2476
					tginitdeferred = 1;
2477

V
Vadim B. Mikheev 已提交
2478 2479
				for (findx = 0; findx < numFuncs; findx++)
				{
2480
					if (strcmp(finfo[findx].oid, tgfuncoid) == 0 &&
2481
						finfo[findx].nargs == 0 &&
V
Vadim B. Mikheev 已提交
2482 2483 2484
						strcmp(finfo[findx].prorettype, "0") == 0)
						break;
				}
2485

V
Vadim B. Mikheev 已提交
2486 2487
				if (findx == numFuncs)
				{
2488
					PGresult   *r;
2489
					int			numFuncs;
2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506

					/*
					 * 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)
					{
B
Bruce Momjian 已提交
2507
						fprintf(stderr, "getTables(): SELECT (funcname) failed for trigger %s.  Explanation from backend: '%s'.\n",
2508
								tgname, PQerrorMessage(g_conn));
2509 2510 2511 2512 2513
						exit_nicely(g_conn);
					}

					/* Sanity: Check we got only one tuple */
					numFuncs = PQntuples(r);
B
Bruce Momjian 已提交
2514 2515 2516
					if (numFuncs != 1)
					{
						fprintf(stderr, "getTables(): SELECT (funcname) for trigger %s returned %d tuples. Expected 1.\n",
2517
								tgname, numFuncs);
2518 2519
						exit_nicely(g_conn);
					}
2520

2521
					tgfunc = strdup(PQgetvalue(r, 0, PQfnumber(r, "proname")));
2522
					PQclear(r);
2523
				}
2524
				else
2525
					tgfunc = strdup(finfo[findx].proname);
B
Bruce Momjian 已提交
2526

2527
				appendPQExpBuffer(delqry, "DROP TRIGGER %s ", fmtId(tgname, force_quotes));
B
Bruce Momjian 已提交
2528
				appendPQExpBuffer(delqry, "ON %s;\n",
B
Bruce Momjian 已提交
2529
								fmtId(tblinfo[i].relname, force_quotes));
2530

B
Hi, all  
Bruce Momjian 已提交
2531
				resetPQExpBuffer(query);
2532 2533 2534 2535 2536
				if (tgisconstraint)
				{
					appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
					appendPQExpBuffer(query, fmtId(PQgetvalue(res2, i2, i_tgconstrname), force_quotes));
				}
2537 2538
				else
				{
2539
					appendPQExpBuffer(query, "CREATE TRIGGER ");
2540
					appendPQExpBuffer(query, fmtId(tgname, force_quotes));
2541
				}
B
Bruce Momjian 已提交
2542
				appendPQExpBufferChar(query, ' ');
V
Vadim B. Mikheev 已提交
2543 2544 2545
				/* Trigger type */
				findx = 0;
				if (TRIGGER_FOR_BEFORE(tgtype))
B
Hi, all  
Bruce Momjian 已提交
2546
					appendPQExpBuffer(query, "BEFORE");
V
Vadim B. Mikheev 已提交
2547
				else
B
Hi, all  
Bruce Momjian 已提交
2548
					appendPQExpBuffer(query, "AFTER");
V
Vadim B. Mikheev 已提交
2549 2550
				if (TRIGGER_FOR_INSERT(tgtype))
				{
B
Hi, all  
Bruce Momjian 已提交
2551
					appendPQExpBuffer(query, " INSERT");
V
Vadim B. Mikheev 已提交
2552 2553 2554 2555 2556
					findx++;
				}
				if (TRIGGER_FOR_DELETE(tgtype))
				{
					if (findx > 0)
B
Hi, all  
Bruce Momjian 已提交
2557
						appendPQExpBuffer(query, " OR DELETE");
V
Vadim B. Mikheev 已提交
2558
					else
B
Hi, all  
Bruce Momjian 已提交
2559
						appendPQExpBuffer(query, " DELETE");
V
Vadim B. Mikheev 已提交
2560 2561 2562
					findx++;
				}
				if (TRIGGER_FOR_UPDATE(tgtype))
2563
				{
V
Vadim B. Mikheev 已提交
2564
					if (findx > 0)
B
Hi, all  
Bruce Momjian 已提交
2565
						appendPQExpBuffer(query, " OR UPDATE");
V
Vadim B. Mikheev 已提交
2566
					else
B
Hi, all  
Bruce Momjian 已提交
2567
						appendPQExpBuffer(query, " UPDATE");
2568
				}
2569 2570
				appendPQExpBuffer(query, " ON %s ", fmtId(tblinfo[i].relname, force_quotes));

2571
				if (tgisconstraint)
2572
				{
2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587
					tgconstrrelid = PQgetvalue(res2, i2, i_tgconstrrelid);

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

						if (PQgetisnull(res2, i2, i_tgconstrrelname))
            			{
                			fprintf(stderr, "getTables(): SELECT produced NULL referenced table name "
											"for trigger '%s' on relation '%s' (oid was %s).\n",
											tgname, tblinfo[i].relname, tgconstrrelid);
                			exit_nicely(g_conn);
            			}

						appendPQExpBuffer(query, " FROM %s", 
										fmtId(PQgetvalue(res2, i2, i_tgconstrrelname), force_quotes));
					}
2588
					if (!tgdeferrable)
2589 2590 2591 2592
						appendPQExpBuffer(query, " NOT");
					appendPQExpBuffer(query, " DEFERRABLE INITIALLY ");
					if (tginitdeferred)
						appendPQExpBuffer(query, "DEFERRED");
2593
					else
2594
						appendPQExpBuffer(query, "IMMEDIATE");
2595

2596 2597 2598
				}

				appendPQExpBuffer(query, " FOR EACH ROW");
2599 2600
				appendPQExpBuffer(query, " EXECUTE PROCEDURE %s (",
								  fmtId(tgfunc, force_quotes));
V
Vadim B. Mikheev 已提交
2601 2602
				for (findx = 0; findx < tgnargs; findx++)
				{
2603
					const char *s;
2604 2605

					for (p = tgargs;;)
V
Vadim B. Mikheev 已提交
2606
					{
2607
						p = strchr(p, '\\');
V
Vadim B. Mikheev 已提交
2608 2609
						if (p == NULL)
						{
B
Bruce Momjian 已提交
2610 2611
							fprintf(stderr, "getTables(): relation '%s': bad argument "
									"string (%s) for trigger '%s'\n",
2612 2613
									tblinfo[i].relname,
									PQgetvalue(res2, i2, i_tgargs),
2614
									tgname);
V
Vadim B. Mikheev 已提交
2615 2616 2617 2618 2619 2620 2621 2622
							exit_nicely(g_conn);
						}
						p++;
						if (*p == '\\')
						{
							p++;
							continue;
						}
2623
						if (p[0] == '0' && p[1] == '0' && p[2] == '0')
V
Vadim B. Mikheev 已提交
2624 2625 2626
							break;
					}
					p--;
2627
					appendPQExpBufferChar(query, '\'');
B
Bruce Momjian 已提交
2628
					for (s = tgargs; s < p;)
V
Vadim B. Mikheev 已提交
2629 2630
					{
						if (*s == '\'')
2631 2632
							appendPQExpBufferChar(query, '\\');
						appendPQExpBufferChar(query, *s++);
V
Vadim B. Mikheev 已提交
2633
					}
B
Bruce Momjian 已提交
2634 2635
					appendPQExpBufferChar(query, '\'');
					appendPQExpBuffer(query, (findx < tgnargs - 1) ? ", " : "");
V
Vadim B. Mikheev 已提交
2636 2637
					tgargs = p + 4;
				}
B
Hi, all  
Bruce Momjian 已提交
2638
				appendPQExpBuffer(query, ");\n");
2639

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

				/*** Initialize trcomments and troids ***/
2643

B
Bruce,  
Bruce Momjian 已提交
2644
				resetPQExpBuffer(query);
2645
				appendPQExpBuffer(query, "TRIGGER %s ",
2646
					fmtId(tgname, force_quotes));
B
Bruce,  
Bruce Momjian 已提交
2647
				appendPQExpBuffer(query, "ON %s",
2648
								fmtId(tblinfo[i].relname, force_quotes));
B
Bruce Momjian 已提交
2649 2650
				tblinfo[i].triggers[i2].tgcomment = strdup(query->data);
				tblinfo[i].triggers[i2].oid = strdup(PQgetvalue(res2, i2, i_tgoid));
2651
				tblinfo[i].triggers[i2].tgname = strdup(fmtId(tgname, false));
B
Bruce Momjian 已提交
2652
				tblinfo[i].triggers[i2].tgdel = strdup(delqry->data);
B
Bruce,  
Bruce Momjian 已提交
2653

2654 2655
				if (tgfunc)
					free(tgfunc);
V
Vadim B. Mikheev 已提交
2656 2657 2658 2659 2660
			}
			PQclear(res2);
		}
		else
			tblinfo[i].triggers = NULL;
2661

2662 2663 2664 2665 2666
	}

	PQclear(res);

	return tblinfo;
2667 2668 2669 2670 2671

}

/*
 * getInherits
2672
 *	  read all the inheritance information
2673 2674
 * from the system catalogs return them in the InhInfo* structure
 *
2675 2676
 * numInherits is set to the number of tables read in
 *
2677 2678
 *
 */
2679
InhInfo    *
2680 2681
getInherits(int *numInherits)
{
2682
	PGresult   *res;
2683 2684
	int			ntups;
	int			i;
2685 2686
	PQExpBuffer query = createPQExpBuffer();
	InhInfo    *inhinfo;
2687

2688
	int			i_inhrelid;
2689
	int			i_inhparent;
2690 2691 2692

	/* find all the inheritance information */

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

B
Hi, all  
Bruce Momjian 已提交
2695
	res = PQexec(g_conn, query->data);
2696 2697 2698
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
2699
		fprintf(stderr, "getInherits(): SELECT failed.  Explanation from backend: '%s'.\n",
B
Bruce Momjian 已提交
2700
				PQerrorMessage(g_conn));
2701 2702 2703 2704 2705 2706 2707 2708 2709
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numInherits = ntups;

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

2710
	i_inhrelid = PQfnumber(res, "inhrelid");
2711 2712 2713 2714
	i_inhparent = PQfnumber(res, "inhparent");

	for (i = 0; i < ntups; i++)
	{
2715
		inhinfo[i].inhrelid = strdup(PQgetvalue(res, i, i_inhrelid));
2716 2717 2718 2719 2720
		inhinfo[i].inhparent = strdup(PQgetvalue(res, i, i_inhparent));
	}

	PQclear(res);
	return inhinfo;
2721 2722 2723 2724
}

/*
 * getTableAttrs -
2725 2726
 *	  for each table in tblinfo, read its attributes types and names
 *
2727
 * this is implemented in a very inefficient way right now, looping
2728
 * through the tblinfo and doing a join per table to find the attrs and their
2729 2730
 * types
 *
2731
 *	modifies tblinfo
2732 2733
 */
void
2734
getTableAttrs(TableInfo *tblinfo, int numTables)
2735
{
2736 2737
	int			i,
				j;
2738
	PQExpBuffer q = createPQExpBuffer();
2739 2740
	int			i_attname;
	int			i_typname;
2741
	int			i_atttypmod;
2742
	int			i_attnotnull;
V
Vadim B. Mikheev 已提交
2743
	int			i_atthasdef;
2744
	int			i_attoid;
2745
	int			i_atttypedefn;
2746
	PGresult   *res;
2747
	int			ntups;
2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762

	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)
2763
			fprintf(stderr, "%s finding the attrs and types for table: '%s' %s\n",
2764 2765 2766 2767
					g_comment_start,
					tblinfo[i].relname,
					g_comment_end);

B
Hi, all  
Bruce Momjian 已提交
2768
		resetPQExpBuffer(q);
2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797

		if (g_fout->remoteVersion < 70100)
		{
			/* Fake the LOJ below */
			appendPQExpBuffer(q, 
						"  SELECT a.oid as attoid, a.attnum, a.attname, t.typname, a.atttypmod, "
						"        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 "
						" UNION ALL SELECT a.oid as attoid, a.attnum, a.attname, NULL as typname, a.atttypmod, "
						"        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 {
			appendPQExpBuffer(q, "SELECT a.oid as attoid, a.attnum, a.attname, t.typname, a.atttypmod, "
								"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 已提交
2798
		res = PQexec(g_conn, q->data);
2799 2800 2801
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
B
Bruce Momjian 已提交
2802
			fprintf(stderr, "getTableAttrs(): SELECT failed.  "
B
Bruce Momjian 已提交
2803
			"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
2804 2805 2806 2807 2808
			exit_nicely(g_conn);
		}

		ntups = PQntuples(res);

B
Bruce,  
Bruce Momjian 已提交
2809
		i_attoid = PQfnumber(res, "attoid");
2810 2811
		i_attname = PQfnumber(res, "attname");
		i_typname = PQfnumber(res, "typname");
2812
		i_atttypmod = PQfnumber(res, "atttypmod");
2813
		i_attnotnull = PQfnumber(res, "attnotnull");
V
Vadim B. Mikheev 已提交
2814
		i_atthasdef = PQfnumber(res, "atthasdef");
2815
		i_atttypedefn = PQfnumber(res, "atttypedefn");
2816 2817

		tblinfo[i].numatts = ntups;
B
Bruce,  
Bruce Momjian 已提交
2818
		tblinfo[i].attoids = (char **) malloc(ntups * sizeof(char *));
2819
		tblinfo[i].attnames = (char **) malloc(ntups * sizeof(char *));
2820
		tblinfo[i].atttypedefns = (char **) malloc(ntups * sizeof(char *));
2821
		tblinfo[i].typnames = (char **) malloc(ntups * sizeof(char *));
2822
		tblinfo[i].atttypmod = (int *) malloc(ntups * sizeof(int));
2823
		tblinfo[i].inhAttrs = (int *) malloc(ntups * sizeof(int));
2824 2825
		tblinfo[i].inhAttrDef = (int *) malloc(ntups * sizeof(int));
		tblinfo[i].inhNotNull = (int *) malloc(ntups * sizeof(int));
2826
		tblinfo[i].notnull = (bool *) malloc(ntups * sizeof(bool));
V
Vadim B. Mikheev 已提交
2827
		tblinfo[i].adef_expr = (char **) malloc(ntups * sizeof(char *));
2828 2829 2830 2831
		tblinfo[i].parentRels = NULL;
		tblinfo[i].numParents = 0;
		for (j = 0; j < ntups; j++)
		{
2832 2833 2834 2835 2836 2837 2838 2839 2840

			/* Sanity check on LOJ */
			if (PQgetisnull(res, j, i_typname))
			{
				fprintf(stderr, "getTableAttrs(): SELECT produced NULL attribute type name for attr %d on table %s.\n",
						j, tblinfo[i].relname);
				exit_nicely(g_conn);
			}

B
Bruce,  
Bruce Momjian 已提交
2841
			tblinfo[i].attoids[j] = strdup(PQgetvalue(res, j, i_attoid));
2842
			tblinfo[i].attnames[j] = strdup(PQgetvalue(res, j, i_attname));
2843
			tblinfo[i].atttypedefns[j] = strdup(PQgetvalue(res, j, i_atttypedefn));
2844
			tblinfo[i].typnames[j] = strdup(PQgetvalue(res, j, i_typname));
2845
			tblinfo[i].atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
2846 2847
			tblinfo[i].inhAttrs[j] = 0; /* this flag is set in
										 * flagInhAttrs() */
2848 2849 2850
			tblinfo[i].inhAttrDef[j] = 0;
			tblinfo[i].inhNotNull[j] = 0;

2851
			tblinfo[i].notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't') ? true : false;
V
Vadim B. Mikheev 已提交
2852 2853 2854
			if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
			{
				PGresult   *res2;
2855
				int			numAttr;
2856

V
Vadim B. Mikheev 已提交
2857
				if (g_verbose)
2858
					fprintf(stderr, "%s finding DEFAULT expression for attr: '%s' %s\n",
V
Vadim B. Mikheev 已提交
2859 2860 2861
							g_comment_start,
							tblinfo[i].attnames[j],
							g_comment_end);
2862

B
Hi, all  
Bruce Momjian 已提交
2863 2864
				resetPQExpBuffer(q);
				appendPQExpBuffer(q, "SELECT adsrc from pg_attrdef "
2865 2866
							 "where adrelid = '%s'::oid and adnum = %d ",
								  tblinfo[i].oid, j + 1);
B
Hi, all  
Bruce Momjian 已提交
2867
				res2 = PQexec(g_conn, q->data);
V
Vadim B. Mikheev 已提交
2868
				if (!res2 ||
2869
					PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
2870
				{
B
Bruce Momjian 已提交
2871 2872
					fprintf(stderr, "getTableAttrs(): SELECT (for DEFAULT) failed.  "
							"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
V
Vadim B. Mikheev 已提交
2873 2874
					exit_nicely(g_conn);
				}
2875 2876 2877

				/* Sanity: Check we got only one tuple */
				numAttr = PQntuples(res2);
B
Bruce Momjian 已提交
2878 2879 2880 2881
				if (numAttr != 1)
				{
					fprintf(stderr, "getTableAttrs(): SELECT (for DEFAULT) for attr %s returned %d tuples. Expected 1.\n",
							tblinfo[i].attnames[j], numAttr);
2882 2883 2884
					exit_nicely(g_conn);
				}

V
Vadim B. Mikheev 已提交
2885 2886 2887 2888 2889
				tblinfo[i].adef_expr[j] = strdup(PQgetvalue(res2, 0, PQfnumber(res2, "adsrc")));
				PQclear(res2);
			}
			else
				tblinfo[i].adef_expr[j] = NULL;
2890 2891 2892
		}
		PQclear(res);
	}
2893 2894 2895 2896 2897
}


/*
 * getIndices
2898
 *	  read all the user-defined indices information
2899 2900
 * from the system catalogs return them in the InhInfo* structure
 *
2901 2902
 * numIndices is set to the number of indices read in
 *
2903 2904
 *
 */
2905
IndInfo    *
2906 2907
getIndices(int *numIndices)
{
2908
	int			i;
2909
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
2910
	PGresult   *res;
2911
	int			ntups;
B
Bruce Momjian 已提交
2912
	IndInfo    *indinfo;
2913 2914 2915 2916 2917 2918 2919 2920

	int			i_indexrelname;
	int			i_indrelname;
	int			i_indamname;
	int			i_indproc;
	int			i_indkey;
	int			i_indclass;
	int			i_indisunique;
2921
	int			i_indoid;
2922 2923
	int			i_oid;
	int			i_indisprimary;
2924 2925 2926 2927 2928

	/*
	 * find all the user-defined indices. We do not handle partial
	 * indices.
	 *
2929
	 * Notice we skip indices on system classes
2930 2931
	 *
	 * this is a 4-way join !!
2932 2933
	 *
	 * XXXX: Use LOJ
2934 2935
	 */

B
Hi, all  
Bruce Momjian 已提交
2936
	appendPQExpBuffer(query,
2937
					  "SELECT i.oid, t1.oid as indoid, t1.relname as indexrelname, t2.relname as indrelname, "
2938
					  "i.indproc, i.indkey, i.indclass, "
B
Bruce Momjian 已提交
2939
				  "a.amname as indamname, i.indisunique, i.indisprimary "
2940 2941 2942
					"from pg_index i, pg_class t1, pg_class t2, pg_am a "
				   "WHERE t1.oid = i.indexrelid and t2.oid = i.indrelid "
					  "and t1.relam = a.oid and i.indexrelid > '%u'::oid "
2943
					  "and t2.relname !~ '^pg_' ",
2944
					  g_last_builtin_oid);
2945

2946 2947 2948
	if (g_fout->remoteVersion < 70100)
		appendPQExpBuffer(query, " and t2.relkind != 'l'");

B
Hi, all  
Bruce Momjian 已提交
2949
	res = PQexec(g_conn, query->data);
2950 2951 2952
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
2953
		fprintf(stderr, "getIndices(): SELECT failed.  "
B
Bruce Momjian 已提交
2954
			"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
2955 2956 2957 2958 2959 2960 2961 2962 2963
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numIndices = ntups;

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

2964 2965
	memset((char *) indinfo, 0, ntups * sizeof(IndInfo));

2966
	i_oid = PQfnumber(res, "oid");
B
Bruce,  
Bruce Momjian 已提交
2967
	i_indoid = PQfnumber(res, "indoid");
2968 2969 2970 2971 2972 2973 2974
	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");
2975
	i_indisprimary = PQfnumber(res, "indisprimary");
2976 2977 2978

	for (i = 0; i < ntups; i++)
	{
2979
		indinfo[i].oid = strdup(PQgetvalue(res, i, i_oid));
B
Bruce,  
Bruce Momjian 已提交
2980
		indinfo[i].indoid = strdup(PQgetvalue(res, i, i_indoid));
2981 2982 2983 2984
		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));
2985 2986 2987 2988 2989 2990
		parseNumericArray(PQgetvalue(res, i, i_indkey),
						  indinfo[i].indkey,
						  INDEX_MAX_KEYS);
		parseNumericArray(PQgetvalue(res, i, i_indclass),
						  indinfo[i].indclass,
						  INDEX_MAX_KEYS);
2991
		indinfo[i].indisunique = strdup(PQgetvalue(res, i, i_indisunique));
2992
		indinfo[i].indisprimary = strdup(PQgetvalue(res, i, i_indisprimary));
2993 2994 2995
	}
	PQclear(res);
	return indinfo;
2996 2997
}

B
Bruce,  
Bruce Momjian 已提交
2998
/*------------------------------------------------------------------
2999
 * dumpComments --
B
Bruce,  
Bruce Momjian 已提交
3000
 *
3001
 * This routine is used to dump any comments associated with the
B
Bruce,  
Bruce Momjian 已提交
3002 3003 3004 3005
 * oid handed to this routine. The routine takes a constant character
 * string for the target part of the object and the oid of the object
 * whose comments are to be dumped. It is perfectly acceptable
 * to hand an oid to this routine which has not been commented. In
3006
 * addition, the routine takes the stdio FILE handle to which the
B
Bruce,  
Bruce Momjian 已提交
3007 3008 3009 3010
 * output should be written.
 *------------------------------------------------------------------
*/

T
Tom Lane 已提交
3011
static void
B
Bruce Momjian 已提交
3012
dumpComment(Archive *fout, const char *target, const char *oid)
3013
{
B
Bruce,  
Bruce Momjian 已提交
3014

3015
	PGresult   *res;
B
Bruce,  
Bruce Momjian 已提交
3016
	PQExpBuffer query;
3017
	int			i_description;
B
Bruce,  
Bruce Momjian 已提交
3018

3019 3020 3021 3022
	/* Comments are SCHEMA not data */
	if (dataOnly)
		return;

B
Bruce,  
Bruce Momjian 已提交
3023 3024 3025 3026 3027 3028 3029 3030 3031
	/*** Build query to find comment ***/

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

	/*** Execute query ***/

	res = PQexec(g_conn, query->data);
3032 3033
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce,  
Bruce Momjian 已提交
3034 3035 3036 3037 3038 3039 3040
		fprintf(stderr, "DumpComment: SELECT failed: '%s'.\n",
				PQerrorMessage(g_conn));
		exit_nicely(g_conn);
	}

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

3041 3042
	if (PQntuples(res) != 0)
	{
B
Bruce,  
Bruce Momjian 已提交
3043
		i_description = PQfnumber(res, "description");
B
Bruce Momjian 已提交
3044
		resetPQExpBuffer(query);
3045
		appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
3046
		formatStringLiteral(query, PQgetvalue(res, 0, i_description), PASS_LFTAB);
3047
		appendPQExpBuffer(query, ";\n");
B
Bruce Momjian 已提交
3048

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

B
Bruce,  
Bruce Momjian 已提交
3052 3053 3054 3055 3056
	}

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

	PQclear(res);
3057

B
Bruce,  
Bruce Momjian 已提交
3058 3059 3060
}

/*------------------------------------------------------------------
3061
 * dumpDBComment --
B
Bruce,  
Bruce Momjian 已提交
3062
 *
3063 3064
 * 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 已提交
3065 3066 3067 3068 3069
 * to dump the schema of the database, then this is the first
 * statement issued.
 *------------------------------------------------------------------
*/

3070
void
B
Bruce Momjian 已提交
3071
dumpDBComment(Archive *fout)
3072
{
B
Bruce,  
Bruce Momjian 已提交
3073

3074
	PGresult   *res;
B
Bruce,  
Bruce Momjian 已提交
3075
	PQExpBuffer query;
3076
	int			i_oid;
B
Bruce,  
Bruce Momjian 已提交
3077 3078 3079 3080

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

	query = createPQExpBuffer();
3081
	appendPQExpBuffer(query, "SELECT oid FROM pg_database WHERE datname = ");
3082
	formatStringLiteral(query, PQdb(g_conn), CONV_ALL);
B
Bruce,  
Bruce Momjian 已提交
3083 3084 3085 3086

	/*** Execute query ***/

	res = PQexec(g_conn, query->data);
3087 3088
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce,  
Bruce Momjian 已提交
3089 3090 3091 3092 3093 3094 3095
		fprintf(stderr, "dumpDBComment: SELECT failed: '%s'.\n",
				PQerrorMessage(g_conn));
		exit_nicely(g_conn);
	}

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

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

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

	PQclear(res);
3107

B
Bruce,  
Bruce Momjian 已提交
3108 3109
}

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

	deps = malloc(sizeof(char*) * 10);
3127 3128 3129 3130 3131

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

		/* skip all the builtin types */
3132
		if (atooid(tinfo[i].oid) <= g_last_builtin_oid)
3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149
			continue;

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

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

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

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

B
Hi, all  
Bruce Momjian 已提交
3164 3165
		resetPQExpBuffer(q);
		appendPQExpBuffer(q,
3166
						  "CREATE TYPE %s "
3167
						  "( internallength = %s, externallength = %s,",
3168 3169
						  fmtId(tinfo[i].typname, force_quotes),
						  tinfo[i].typlen,
3170 3171 3172 3173 3174 3175 3176 3177 3178 3179
						  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));
3180
		formatStringLiteral(q, tinfo[i].typdefault, CONV_ALL);
3181 3182 3183

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

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

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

			(*deps)[depIdx++] = strdup(tinfo[i].typelem);
3200 3201
		}
		if (tinfo[i].passedbyvalue)
B
Hi, all  
Bruce Momjian 已提交
3202
			appendPQExpBuffer(q, ",passedbyvalue);\n");
3203
		else
B
Hi, all  
Bruce Momjian 已提交
3204
			appendPQExpBuffer(q, ");\n");
3205

3206 3207 3208
		(*deps)[depIdx++] = NULL; /* End of List */

		ArchiveEntry(fout, tinfo[i].oid, tinfo[i].typname, "TYPE", deps,
B
Bruce Momjian 已提交
3209
				  q->data, delq->data, "", tinfo[i].usename, NULL, NULL);
B
Bruce,  
Bruce Momjian 已提交
3210 3211 3212 3213

		/*** Dump Type Comments ***/

		resetPQExpBuffer(q);
B
Bruce Momjian 已提交
3214 3215
		resetPQExpBuffer(delq);

B
Bruce,  
Bruce Momjian 已提交
3216 3217 3218
		appendPQExpBuffer(q, "TYPE %s", fmtId(tinfo[i].typname, force_quotes));
		dumpComment(fout, q->data, tinfo[i].oid);

B
Bruce Momjian 已提交
3219
		resetPQExpBuffer(q);
3220
	}
3221 3222
}

3223 3224
/*
 * dumpProcLangs
B
Bruce Momjian 已提交
3225
 *		  writes out to fout the queries to recreate user-defined procedural languages
3226 3227 3228
 *
 */
void
B
Bruce Momjian 已提交
3229
dumpProcLangs(Archive *fout, FuncInfo *finfo, int numFuncs,
B
Bruce Momjian 已提交
3230
			  TypeInfo *tinfo, int numTypes)
3231
{
3232 3233
	PGresult   *res;
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
3234 3235
	PQExpBuffer defqry = createPQExpBuffer();
	PQExpBuffer delqry = createPQExpBuffer();
3236
	int			ntups;
B
Bruce Momjian 已提交
3237
	int			i_oid;
3238 3239 3240 3241
	int			i_lanname;
	int			i_lanpltrusted;
	int			i_lanplcallfoid;
	int			i_lancompiler;
3242
	Oid			lanoid;
3243 3244 3245
	char	   *lanname;
	char	   *lancompiler;
	const char *lanplcallfoid;
3246 3247 3248
	int			i,
				fidx;

B
Bruce Momjian 已提交
3249
	appendPQExpBuffer(query, "SELECT oid, * FROM pg_language "
3250 3251
					  "WHERE lanispl "
					  "ORDER BY oid");
B
Hi, all  
Bruce Momjian 已提交
3252
	res = PQexec(g_conn, query->data);
3253 3254 3255
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
3256
		fprintf(stderr, "dumpProcLangs(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
3257 3258 3259 3260
		exit_nicely(g_conn);
	}
	ntups = PQntuples(res);

B
Bruce Momjian 已提交
3261 3262 3263 3264
	i_lanname = PQfnumber(res, "lanname");
	i_lanpltrusted = PQfnumber(res, "lanpltrusted");
	i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
	i_lancompiler = PQfnumber(res, "lancompiler");
B
Bruce Momjian 已提交
3265
	i_oid = PQfnumber(res, "oid");
3266

B
Bruce Momjian 已提交
3267 3268
	for (i = 0; i < ntups; i++)
	{
3269
		lanoid = atooid(PQgetvalue(res, i, i_oid));
3270 3271 3272
		if (lanoid <= g_last_builtin_oid)
			continue;

3273
		lanplcallfoid = PQgetvalue(res, i, i_lanplcallfoid);
3274 3275


3276 3277 3278 3279 3280 3281 3282
		for (fidx = 0; fidx < numFuncs; fidx++)
		{
			if (!strcmp(finfo[fidx].oid, lanplcallfoid))
				break;
		}
		if (fidx >= numFuncs)
		{
B
Bruce Momjian 已提交
3283
			fprintf(stderr, "dumpProcLangs(): handler procedure for "
B
Bruce Momjian 已提交
3284
			   "language %s not found\n", PQgetvalue(res, i, i_lanname));
3285 3286 3287 3288 3289
			exit_nicely(g_conn);
		}

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

3290 3291
		lanname = PQgetvalue(res, i, i_lanname);
		lancompiler = PQgetvalue(res, i, i_lancompiler);
3292

3293
		appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE ");
3294
		formatStringLiteral(delqry, lanname, CONV_ALL);
3295
		appendPQExpBuffer(delqry, ";\n");
3296

3297 3298 3299
		appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE ",
						  (PQgetvalue(res, i, i_lanpltrusted)[0] == 't') ?
						  "TRUSTED " : "");
3300
		formatStringLiteral(defqry, lanname, CONV_ALL);
3301 3302
		appendPQExpBuffer(defqry, " HANDLER %s LANCOMPILER ",
						  fmtId(finfo[fidx].proname, force_quotes));
3303
		formatStringLiteral(defqry, lancompiler, CONV_ALL);
3304
		appendPQExpBuffer(defqry, ";\n");
3305

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

3309 3310
		resetPQExpBuffer(defqry);
		resetPQExpBuffer(delqry);
3311 3312 3313 3314 3315 3316
	}

	PQclear(res);

}

3317 3318
/*
 * dumpFuncs
3319
 *	  writes out to fout the queries to recreate all the user-defined functions
3320 3321 3322
 *
 */
void
B
Bruce Momjian 已提交
3323
dumpFuncs(Archive *fout, FuncInfo *finfo, int numFuncs,
3324
		  TypeInfo *tinfo, int numTypes)
3325
{
3326
	int			i;
3327 3328 3329

	for (i = 0; i < numFuncs; i++)
		dumpOneFunc(fout, finfo, i, tinfo, numTypes);
3330 3331 3332 3333
}

/*
 * dumpOneFunc:
3334 3335
 *	  dump out only one function,  the index of which is given in the third
 *	argument
3336 3337 3338
 *
 */

3339
static void
B
Bruce Momjian 已提交
3340
dumpOneFunc(Archive *fout, FuncInfo *finfo, int i,
3341
			TypeInfo *tinfo, int numTypes)
3342
{
3343
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3344 3345
	PQExpBuffer fn = createPQExpBuffer();
	PQExpBuffer delqry = createPQExpBuffer();
B
Bruce,  
Bruce Momjian 已提交
3346
	PQExpBuffer fnlist = createPQExpBuffer();
B
Bruce Momjian 已提交
3347
	int			j;
3348
	PQExpBuffer asPart = createPQExpBuffer();
3349
	char		func_lang[NAMEDATALEN + 1];
3350 3351 3352 3353
	PGresult   *res;
	int			nlangs;
	int			i_lanname;
	char		query[256];
3354

B
Bruce Momjian 已提交
3355 3356 3357 3358
	char	   *listSep;
	char	   *listSepComma = ",";
	char	   *listSepNone = "";
	char	   *rettypename;
3359

3360 3361 3362 3363 3364
	if (finfo[i].dumped)
		return;
	else
		finfo[i].dumped = 1;

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

3367 3368 3369 3370 3371
	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 已提交
3372
	{
3373 3374
		fprintf(stderr, "dumpOneFunc(): SELECT for procedural language failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
		exit_nicely(g_conn);
B
Bruce Momjian 已提交
3375
	}
3376 3377 3378
	nlangs = PQntuples(res);

	if (nlangs != 1)
B
Bruce Momjian 已提交
3379
	{
3380 3381
		fprintf(stderr, "dumpOneFunc(): procedural language for function %s not found\n", finfo[i].proname);
		exit_nicely(g_conn);
B
Bruce Momjian 已提交
3382 3383
	}

3384
	i_lanname = PQfnumber(res, "lanname");
3385

3386
	/*
B
Bruce Momjian 已提交
3387 3388
	 * See backend/commands/define.c for details of how the 'AS' clause is
	 * used.
3389 3390 3391
	 */
	if (strcmp(finfo[i].probin, "-") != 0)
	{
3392
		appendPQExpBuffer(asPart, "AS ");
3393
		formatStringLiteral(asPart, finfo[i].probin, CONV_ALL);
3394
		if (strcmp(finfo[i].prosrc, "-") != 0)
3395 3396
		{
			appendPQExpBuffer(asPart, ", ");
3397
			formatStringLiteral(asPart, finfo[i].prosrc, PASS_LFTAB);
3398
		}
3399 3400 3401 3402
	}
	else
	{
		if (strcmp(finfo[i].prosrc, "-") != 0)
3403 3404
		{
			appendPQExpBuffer(asPart, "AS ");
3405
			formatStringLiteral(asPart, finfo[i].prosrc, PASS_LFTAB);
3406
		}
3407 3408
	}

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

3411
	PQclear(res);
B
Bruce Momjian 已提交
3412

B
Bruce Momjian 已提交
3413 3414
	resetPQExpBuffer(fn);
	appendPQExpBuffer(fn, "%s (", fmtId(finfo[i].proname, force_quotes));
3415 3416
	for (j = 0; j < finfo[i].nargs; j++)
	{
B
Bruce Momjian 已提交
3417
		char	   *typname;
3418

3419
		typname = findTypeByOid(tinfo, numTypes, finfo[i].argtypes[j], zeroAsOpaque);
3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434
		if (typname == NULL)
		{
			fprintf(stderr, "Notice: function \"%s\" is not dumped.\n",
					finfo[i].proname);

			fprintf(stderr, "Reason: the %d th argument type name (oid %s) not found.\n",
					j, finfo[i].argtypes[j]);
			resetPQExpBuffer(q);
			resetPQExpBuffer(fn);
			resetPQExpBuffer(delqry);
			resetPQExpBuffer(fnlist);
			resetPQExpBuffer(asPart);
			return;
		}

B
Bruce Momjian 已提交
3435 3436 3437
		appendPQExpBuffer(fn, "%s%s",
						  (j > 0) ? "," : "",
						  typname);
B
Bruce,  
Bruce Momjian 已提交
3438
		appendPQExpBuffer(fnlist, "%s%s",
B
Bruce Momjian 已提交
3439 3440
						  (j > 0) ? "," : "",
						  typname);
3441
	}
B
Bruce Momjian 已提交
3442 3443 3444
	appendPQExpBuffer(fn, ")");

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

3447 3448 3449 3450 3451 3452 3453 3454 3455
	rettypename = findTypeByOid(tinfo, numTypes, finfo[i].prorettype, zeroAsOpaque);

	if (rettypename == NULL)
	{
		fprintf(stderr, "Notice: function \"%s\" is not dumped.\n",
				finfo[i].proname);

		fprintf(stderr, "Reason: return type name (oid %s) not found.\n",
				finfo[i].prorettype);
B
Bruce Momjian 已提交
3456 3457 3458 3459 3460 3461
		resetPQExpBuffer(q);
		resetPQExpBuffer(fn);
		resetPQExpBuffer(delqry);
		resetPQExpBuffer(fnlist);
		resetPQExpBuffer(asPart);
		return;
3462 3463
	}

B
Bruce Momjian 已提交
3464
	resetPQExpBuffer(q);
B
Bruce Momjian 已提交
3465
	appendPQExpBuffer(q, "CREATE FUNCTION %s ", fn->data);
3466 3467
	appendPQExpBuffer(q, "RETURNS %s%s %s LANGUAGE ",
					  (finfo[i].retset) ? "SETOF " : "",
3468
					  rettypename,
3469
					  asPart->data);
3470
	formatStringLiteral(q, func_lang, CONV_ALL);
3471

B
Bruce Momjian 已提交
3472
	if (finfo[i].iscachable || finfo[i].isstrict)		/* OR in new attrs here */
3473
	{
3474 3475 3476
		appendPQExpBuffer(q, " WITH (");
		listSep = listSepNone;

B
Bruce Momjian 已提交
3477 3478
		if (finfo[i].iscachable)
		{
3479 3480 3481 3482
			appendPQExpBuffer(q, "%s iscachable", listSep);
			listSep = listSepComma;
		}

B
Bruce Momjian 已提交
3483 3484
		if (finfo[i].isstrict)
		{
3485 3486 3487 3488
			appendPQExpBuffer(q, "%s isstrict", listSep);
			listSep = listSepComma;
		}
		appendPQExpBuffer(q, " )");
3489 3490 3491 3492
	}

	appendPQExpBuffer(q, ";\n");

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

B
Bruce,  
Bruce Momjian 已提交
3496 3497 3498 3499 3500 3501 3502 3503
	/*** Dump Function Comments ***/

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

3504 3505 3506 3507
}

/*
 * dumpOprs
3508
 *	  writes out to fout the queries to recreate all the user-defined operators
3509 3510
 *
 */
3511
void
B
Bruce Momjian 已提交
3512
dumpOprs(Archive *fout, OprInfo *oprinfo, int numOperators,
3513
		 TypeInfo *tinfo, int numTypes)
3514
{
3515 3516 3517 3518 3519 3520
#define OPR_NOTICE(arg) {\
		fprintf(stderr, "Notice: operator \"%s\"(oid %s) is not dumped.\n",oprinfo[i].oprname, oprinfo[i].oid);\
	fprintf(stderr, "Reason: " CppAsString(arg));\
	fprintf (stderr, " (oid %s) not found.\n",oprinfo[i].arg);\
	}

B
Bruce Momjian 已提交
3521
	int			i;
3522
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3523
	PQExpBuffer delq = createPQExpBuffer();
3524 3525 3526 3527 3528 3529 3530 3531
	PQExpBuffer leftarg = createPQExpBuffer();
	PQExpBuffer rightarg = createPQExpBuffer();
	PQExpBuffer commutator = createPQExpBuffer();
	PQExpBuffer negator = createPQExpBuffer();
	PQExpBuffer restrictor = createPQExpBuffer();
	PQExpBuffer join = createPQExpBuffer();
	PQExpBuffer sort1 = createPQExpBuffer();
	PQExpBuffer sort2 = createPQExpBuffer();
3532 3533 3534

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

B
Hi, all  
Bruce Momjian 已提交
3537 3538 3539 3540 3541 3542 3543 3544 3545
		resetPQExpBuffer(leftarg);
		resetPQExpBuffer(rightarg);
		resetPQExpBuffer(commutator);
		resetPQExpBuffer(negator);
		resetPQExpBuffer(restrictor);
		resetPQExpBuffer(join);
		resetPQExpBuffer(sort1);
		resetPQExpBuffer(sort2);

3546
		/* skip all the builtin oids */
3547
		if (atooid(oprinfo[i].oid) <= g_last_builtin_oid)
3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563
			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 已提交
3564 3565
			name = findTypeByOid(tinfo, numTypes,
								 oprinfo[i].oprleft, zeroAsOpaque);
3566 3567 3568 3569 3570
			if (name == NULL)
			{
				OPR_NOTICE(oprleft);
				continue;
			}
B
Bruce Momjian 已提交
3571
			appendPQExpBuffer(leftarg, ",\n\tLEFTARG = %s ", name);
3572
		}
3573

3574 3575 3576
		if (strcmp(oprinfo[i].oprkind, "l") == 0 ||
			strcmp(oprinfo[i].oprkind, "b") == 0)
		{
B
Bruce Momjian 已提交
3577 3578
			name = findTypeByOid(tinfo, numTypes,
								 oprinfo[i].oprright, zeroAsOpaque);
3579 3580 3581 3582 3583 3584
			if (name == NULL)
			{
				OPR_NOTICE(oprright);
				continue;
			}
			appendPQExpBuffer(rightarg, ",\n\tRIGHTARG = %s ", name);
3585
		}
3586

B
Hi, all  
Bruce Momjian 已提交
3587
		if (!(strcmp(oprinfo[i].oprcom, "0") == 0))
3588 3589 3590 3591 3592 3593 3594 3595 3596
		{
			name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprcom);
			if (name == NULL)
			{
				OPR_NOTICE(oprcom);
				continue;
			}
			appendPQExpBuffer(commutator, ",\n\tCOMMUTATOR = %s ", name);
		}
3597

B
Hi, all  
Bruce Momjian 已提交
3598
		if (!(strcmp(oprinfo[i].oprnegate, "0") == 0))
3599 3600 3601 3602 3603 3604 3605 3606 3607
		{
			name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprnegate);
			if (name == NULL)
			{
				OPR_NOTICE(oprnegate);
				continue;
			}
			appendPQExpBuffer(negator, ",\n\tNEGATOR = %s ", name);
		}
3608

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

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

B
Hi, all  
Bruce Momjian 已提交
3615
		if (!(strcmp(oprinfo[i].oprlsortop, "0") == 0))
3616
		{
B
Bruce Momjian 已提交
3617
			name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprlsortop);
3618 3619 3620 3621 3622 3623 3624
			if (name == NULL)
			{
				OPR_NOTICE(oprlsortop);
				continue;
			}
			appendPQExpBuffer(sort1, ",\n\tSORT1 = %s ", name);
		}
3625

B
Hi, all  
Bruce Momjian 已提交
3626
		if (!(strcmp(oprinfo[i].oprrsortop, "0") == 0))
3627
		{
B
Bruce Momjian 已提交
3628
			name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprrsortop);
3629 3630 3631 3632 3633 3634 3635
			if (name == NULL)
			{
				OPR_NOTICE(oprrsortop);
				continue;
			}
			appendPQExpBuffer(sort2, ",\n\tSORT2 = %s ", name);
		}
3636

B
Bruce Momjian 已提交
3637 3638
		resetPQExpBuffer(delq);
		appendPQExpBuffer(delq, "DROP OPERATOR %s (%s", oprinfo[i].oprname,
B
Bruce Momjian 已提交
3639
		findTypeByOid(tinfo, numTypes, oprinfo[i].oprleft, zeroAsOpaque));
B
Bruce Momjian 已提交
3640
		appendPQExpBuffer(delq, ", %s);\n",
B
Bruce Momjian 已提交
3641
						  findTypeByOid(tinfo, numTypes, oprinfo[i].oprright, zeroAsOpaque));
3642

B
Hi, all  
Bruce Momjian 已提交
3643 3644
		resetPQExpBuffer(q);
		appendPQExpBuffer(q,
3645 3646 3647 3648 3649 3650 3651 3652 3653
						  "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 已提交
3654
		  (strcmp(oprinfo[i].oprcanhash, "t") == 0) ? ",\n\tHASHES" : "",
3655 3656 3657
						  join->data,
						  sort1->data,
						  sort2->data);
3658

B
Bruce Momjian 已提交
3659
		ArchiveEntry(fout, oprinfo[i].oid, oprinfo[i].oprname, "OPERATOR", NULL,
B
Bruce Momjian 已提交
3660
				q->data, delq->data, "", oprinfo[i].usename, NULL, NULL);
3661
	}
3662 3663 3664 3665
}

/*
 * dumpAggs
3666
 *	  writes out to fout the queries to create all the user-defined aggregates
3667 3668 3669
 *
 */
void
B
Bruce Momjian 已提交
3670
dumpAggs(Archive *fout, AggInfo *agginfo, int numAggs,
3671
		 TypeInfo *tinfo, int numTypes)
3672
{
3673
#define AGG_NOTICE(arg) {\
3674 3675 3676 3677 3678 3679 3680
		resetPQExpBuffer(q);\
		appendPQExpBuffer(q, "-- Notice: aggregate \"%s\"(oid %s) is not dumped.\n",agginfo[i].aggname, agginfo[i].oid);\
		appendPQExpBuffer(q, "-- Reason: " CppAsString(arg) );\
		appendPQExpBuffer(q, " (oid %s) not found.\n",agginfo[i].arg);\
		fprintf(stderr, q->data);\
		ArchiveEntry(fout, agginfo[i].oid, aggSig->data, "WARNING", NULL,\
					q->data, "" /* Del */, "", agginfo[i].usename, NULL, NULL);\
3681 3682
	}

B
Bruce Momjian 已提交
3683
	int			i;
3684
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3685 3686
	PQExpBuffer delq = createPQExpBuffer();
	PQExpBuffer aggSig = createPQExpBuffer();
3687
	PQExpBuffer details = createPQExpBuffer();
3688 3689 3690

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

3693
		resetPQExpBuffer(details);
B
Hi, all  
Bruce Momjian 已提交
3694

3695
		/* skip all the builtin oids */
3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711
		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)
		{
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "-- WARNING: Aggregate %s could not be dumped correctly for this database version - ignored\n",
									aggSig->data);
			fprintf(stderr, q->data);

			ArchiveEntry(fout, agginfo[i].oid, aggSig->data, "WARNING", NULL,
					q->data, "" /* Del */, "", agginfo[i].usename, NULL, NULL);
3712
			continue;
3713
		}
3714

3715 3716 3717 3718 3719 3720 3721
		name = findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype, zeroAsAny + useBaseTypeName);
		if (name == NULL)
		{
			AGG_NOTICE(aggbasetype);
			continue;
		}
		appendPQExpBuffer(details, "BASETYPE = %s, ", name);
3722

3723 3724 3725 3726 3727 3728
		name = findTypeByOid(tinfo, numTypes, agginfo[i].aggtranstype, zeroAsOpaque + useBaseTypeName);
		if (name == NULL)
		{
			AGG_NOTICE(aggtranstype);
			continue;
		}
3729 3730
		appendPQExpBuffer(details,
						  "SFUNC = %s, STYPE = %s",
3731
						  agginfo[i].aggtransfn, name);
3732

3733
		if (agginfo[i].agginitval)
3734 3735
		{
			appendPQExpBuffer(details, ", INITCOND = ");
3736
			formatStringLiteral(details, agginfo[i].agginitval, CONV_ALL);
3737
		}
3738

B
Hi, all  
Bruce Momjian 已提交
3739
		if (!(strcmp(agginfo[i].aggfinalfn, "-") == 0))
3740 3741
			appendPQExpBuffer(details, ", FINALFUNC = %s",
							  agginfo[i].aggfinalfn);
3742

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

B
Hi, all  
Bruce Momjian 已提交
3746
		resetPQExpBuffer(q);
3747
		appendPQExpBuffer(q, "CREATE AGGREGATE %s ( %s );\n",
3748
						  agginfo[i].aggname,
3749
						  details->data);
3750

B
Bruce Momjian 已提交
3751
		ArchiveEntry(fout, agginfo[i].oid, aggSig->data, "AGGREGATE", NULL,
B
Bruce Momjian 已提交
3752
				q->data, delq->data, "", agginfo[i].usename, NULL, NULL);
B
Bruce,  
Bruce Momjian 已提交
3753 3754 3755 3756

		/*** Dump Aggregate Comments ***/

		resetPQExpBuffer(q);
3757
		appendPQExpBuffer(q, "AGGREGATE %s %s", agginfo[i].aggname,
3758
						  findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype, zeroAsOpaque + useBaseTypeName));
B
Bruce,  
Bruce Momjian 已提交
3759 3760
		dumpComment(fout, q->data, agginfo[i].oid);

3761
	}
3762 3763
}

3764 3765 3766 3767 3768
/*
 * These are some support functions to fix the acl problem of pg_dump
 *
 * Matthew C. Aycock 12/02/97
 */
3769 3770 3771

/* Append a keyword to a keyword list, inserting comma if needed.
 * Caller must make aclbuf big enough for all possible keywords.
3772
 */
3773
static void
B
Bruce Momjian 已提交
3774
AddAcl(char *aclbuf, const char *keyword)
3775
{
3776 3777 3778
	if (*aclbuf)
		strcat(aclbuf, ",");
	strcat(aclbuf, keyword);
3779
}
3780

3781
/*
3782
 * This will take a string of 'arwR' and return a malloced,
3783 3784
 * comma delimited string of SELECT,INSERT,UPDATE,DELETE,RULE
 */
V
Vadim B. Mikheev 已提交
3785
static char *
3786
GetPrivileges(const char *s)
3787
{
3788
	char		aclbuf[100];
3789

3790
	aclbuf[0] = '\0';
3791

B
Bruce Momjian 已提交
3792
	if (strchr(s, 'a'))
3793
		AddAcl(aclbuf, "INSERT");
3794

B
Bruce Momjian 已提交
3795
	if (strchr(s, 'w'))
3796
		AddAcl(aclbuf, "UPDATE,DELETE");
B
Bruce Momjian 已提交
3797 3798

	if (strchr(s, 'r'))
3799
		AddAcl(aclbuf, "SELECT");
3800

3801
	if (strchr(s, 'R'))
3802
		AddAcl(aclbuf, "RULE");
3803

3804 3805 3806
	/* Special-case when they're all there */
	if (strcmp(aclbuf, "INSERT,UPDATE,DELETE,SELECT,RULE") == 0)
		return strdup("ALL");
3807

3808
	return strdup(aclbuf);
3809
}
3810

B
Bruce Momjian 已提交
3811
/*
B
Bruce Momjian 已提交
3812
 * The name says it all; a function to append a string is the dest
B
Bruce Momjian 已提交
3813 3814
 * is big enough. If not, it does a realloc.
 */
B
Bruce Momjian 已提交
3815 3816
static void
strcatalloc(char **dest, int *dSize, char *src)
B
Bruce Momjian 已提交
3817
{
B
Bruce Momjian 已提交
3818 3819 3820 3821 3822 3823 3824 3825 3826 3827
	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 已提交
3828 3829


B
Bruce Momjian 已提交
3830 3831
/*
 * dumpACL:
3832 3833
 *	  Write out grant/revoke information
 *	  Called for sequences and tables
B
Bruce Momjian 已提交
3834 3835
 */

3836
static void
B
Bruce Momjian 已提交
3837
dumpACL(Archive *fout, TableInfo tbinfo)
B
Bruce Momjian 已提交
3838
{
B
Bruce Momjian 已提交
3839 3840
	const char *acls = tbinfo.relacl;
	char	   *aclbuf,
B
Bruce Momjian 已提交
3841 3842 3843
			   *tok,
			   *eqpos,
			   *priv;
B
Bruce Momjian 已提交
3844
	char	   *sql;
B
Bruce Momjian 已提交
3845
	char		tmp[1024];
B
Bruce Momjian 已提交
3846
	int			sSize = 4096;
3847 3848 3849 3850

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

B
Bruce Momjian 已提交
3851 3852 3853
	/*
	 * Allocate a larginsh buffer for the output SQL.
	 */
B
Bruce Momjian 已提交
3854
	sql = (char *) malloc(sSize);
B
Bruce Momjian 已提交
3855

B
Bruce Momjian 已提交
3856 3857 3858
	/*
	 * Revoke Default permissions for PUBLIC. Is this actually necessary,
	 * or is it just a waste of time?
3859
	 */
B
Bruce Momjian 已提交
3860
	sprintf(sql, "REVOKE ALL on %s from PUBLIC;\n",
3861
			fmtId(tbinfo.relname, force_quotes));
3862 3863 3864

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

3866 3867
	/* Scan comma-separated ACL items */
	for (tok = strtok(aclbuf, ","); tok != NULL; tok = strtok(NULL, ","))
3868
	{
3869

B
Bruce Momjian 已提交
3870 3871 3872
		/*
		 * Token may start with '{' and/or '"'.  Actually only the start
		 * of the string should have '{', but we don't verify that.
3873 3874 3875 3876 3877 3878 3879 3880
		 */
		if (*tok == '{')
			tok++;
		if (*tok == '"')
			tok++;

		/* User name is string up to = in tok */
		eqpos = strchr(tok, '=');
B
Bruce Momjian 已提交
3881
		if (!eqpos)
B
Bruce Momjian 已提交
3882
		{
3883 3884
			fprintf(stderr, "Could not parse ACL list ('%s') for '%s'...Exiting!\n",
					acls, tbinfo.relname);
B
Bruce Momjian 已提交
3885 3886 3887
			exit_nicely(g_conn);
		}

B
Bruce Momjian 已提交
3888 3889 3890 3891
		/*
		 * Parse the privileges (right-hand side).	Skip if there are
		 * none.
		 */
3892 3893
		priv = GetPrivileges(eqpos + 1);
		if (*priv)
3894
		{
B
Bruce Momjian 已提交
3895
			sprintf(tmp, "GRANT %s on %s to ",
3896
					priv, fmtId(tbinfo.relname, force_quotes));
B
Bruce Momjian 已提交
3897
			strcatalloc(&sql, &sSize, tmp);
B
Bruce Momjian 已提交
3898 3899 3900

			/*
			 * Note: fmtId() can only be called once per printf, so don't
3901 3902 3903 3904 3905
			 * try to merge printing of username into the above printf.
			 */
			if (eqpos == tok)
			{
				/* Empty left-hand side means "PUBLIC" */
B
Bruce Momjian 已提交
3906
				strcatalloc(&sql, &sSize, "PUBLIC;\n");
3907
			}
3908
			else
3909 3910
			{
				*eqpos = '\0';	/* it's ok to clobber aclbuf */
3911
				if (strncmp(tok, "group ", strlen("group ")) == 0)
B
Bruce Momjian 已提交
3912
					sprintf(tmp, "GROUP %s;\n",
3913 3914
							fmtId(tok + strlen("group "), force_quotes));
				else
B
Bruce Momjian 已提交
3915 3916
					sprintf(tmp, "%s;\n", fmtId(tok, force_quotes));
				strcatalloc(&sql, &sSize, tmp);
3917
			}
3918
		}
3919
		free(priv);
B
Bruce Momjian 已提交
3920
	}
3921 3922

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

3924
	ArchiveEntry(fout, tbinfo.oid, tbinfo.relname, "ACL", NULL, sql, "", "", "", NULL, NULL);
B
Bruce Momjian 已提交
3925

B
Bruce Momjian 已提交
3926 3927
}

3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982
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));
	}
}
3983

3984 3985
/*
 * dumpTables:
3986
 *	  write out to fout all the user-define tables
3987
 */
3988

3989
void
B
Bruce Momjian 已提交
3990
dumpTables(Archive *fout, TableInfo *tblinfo, int numTables,
3991
		   IndInfo *indinfo, int numIndices,
3992 3993
		   InhInfo *inhinfo, int numInherits,
		   TypeInfo *tinfo, int numTypes, const char *tablename,
B
Bruce Momjian 已提交
3994 3995
		   const bool aclsSkip, const bool oids,
		   const bool schemaOnly, const bool dataOnly)
3996
{
3997 3998
	int			i,
				j,
B
Bruce Momjian 已提交
3999
				k;
4000
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
4001
	PQExpBuffer delq = createPQExpBuffer();
4002
	char	   *serialSeq = NULL;		/* implicit sequence name created
B
Bruce Momjian 已提交
4003 4004 4005 4006
										 * by SERIAL datatype */
	const char *serialSeqSuffix = "_id_seq";	/* suffix for implicit
												 * SERIAL sequences */
	char	  **parentRels;		/* list of names of parent relations */
4007
	int			numParents;
B
Bruce Momjian 已提交
4008
	int			actual_atts;	/* number of attrs in this CREATE statment */
4009
	char	   *reltypename;
4010
	char	   *objoid;
4011

V
Vadim B. Mikheev 已提交
4012
	/* First - dump SEQUENCEs */
4013
	if (tablename && strlen(tablename) > 0)
B
Bruce Momjian 已提交
4014 4015 4016 4017 4018
	{
		serialSeq = malloc(strlen(tablename) + strlen(serialSeqSuffix) + 1);
		strcpy(serialSeq, tablename);
		strcat(serialSeq, serialSeqSuffix);
	}
V
Vadim B. Mikheev 已提交
4019 4020 4021 4022
	for (i = 0; i < numTables; i++)
	{
		if (!(tblinfo[i].sequence))
			continue;
B
Bruce Momjian 已提交
4023
		if (!tablename || (!strcmp(tblinfo[i].relname, tablename))
B
Bruce Momjian 已提交
4024
			|| (serialSeq && !strcmp(tblinfo[i].relname, serialSeq)))
V
Vadim B. Mikheev 已提交
4025
		{
B
Bruce Momjian 已提交
4026
			/* becomeUser(fout, tblinfo[i].usename); */
4027
			dumpSequence(fout, tblinfo[i], schemaOnly, dataOnly);
4028
			if (!aclsSkip)
B
Bruce Momjian 已提交
4029
				dumpACL(fout, tblinfo[i]);
V
Vadim B. Mikheev 已提交
4030 4031
		}
	}
B
Bruce Momjian 已提交
4032
	if (tablename)
B
Bruce Momjian 已提交
4033
		free(serialSeq);
4034

4035 4036
	for (i = 0; i < numTables; i++)
	{
4037
		if (tblinfo[i].sequence)/* already dumped */
V
Vadim B. Mikheev 已提交
4038
			continue;
4039

4040
		if (!tablename || (!strcmp(tblinfo[i].relname, tablename)) || (strlen(tablename) == 0))
4041 4042
		{

4043 4044
			resetPQExpBuffer(delq);
			resetPQExpBuffer(q);
4045

4046 4047 4048 4049
			/* Use the view definition if there is one */
			if (tblinfo[i].viewdef != NULL)
			{
				reltypename = "VIEW";
4050
				objoid = tblinfo[i].viewoid;
4051
				appendPQExpBuffer(delq, "DROP VIEW %s;\n", fmtId(tblinfo[i].relname, force_quotes));
4052
				appendPQExpBuffer(q, "CREATE VIEW %s as %s\n", fmtId(tblinfo[i].relname, force_quotes), tblinfo[i].viewdef);
4053

4054 4055
			}
			else
4056
			{
4057
				reltypename = "TABLE";
4058
				objoid = tblinfo[i].oid;
4059 4060
				parentRels = tblinfo[i].parentRels;
				numParents = tblinfo[i].numParents;
B
Bruce Momjian 已提交
4061

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

4064 4065 4066 4067 4068 4069
				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)
4070
					{
4071 4072 4073 4074 4075
						/* Format properly if not first attr */
						if (actual_atts > 0)
							appendPQExpBuffer(q, ",\n\t");

						/* Attr name & type */
4076 4077 4078 4079 4080 4081 4082 4083
						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);
						}
4084 4085

						/* Default value */
4086
						if (tblinfo[i].adef_expr[j] != NULL && tblinfo[i].inhAttrDef[j] == 0)
4087
							appendPQExpBuffer(q, " DEFAULT %s",
B
Bruce Momjian 已提交
4088
											  tblinfo[i].adef_expr[j]);
4089 4090

						/* Not Null constraint */
4091
						if (tblinfo[i].notnull[j] && tblinfo[i].inhNotNull[j] == 0)
4092 4093 4094 4095
							appendPQExpBuffer(q, " NOT NULL");

						actual_atts++;
					}
4096
				}
B
Hi all  
Bruce Momjian 已提交
4097

4098 4099


4100 4101 4102 4103 4104 4105 4106
				/* 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 已提交
4107
									  tblinfo[i].check_expr[k]);
4108
				}
4109

4110 4111
				/* Primary Key */
				if (tblinfo[i].pkIndexOid != NULL)
4112
				{
B
Bruce Momjian 已提交
4113
					PQExpBuffer consDef;
4114 4115 4116 4117

					/* Find the corresponding index */
					for (k = 0; k < numIndices; k++)
					{
B
Bruce Momjian 已提交
4118
						if (strcmp(indinfo[k].oid, tblinfo[i].pkIndexOid) == 0)
4119 4120 4121 4122 4123 4124
							break;
					}

					if (k >= numIndices)
					{
						fprintf(stderr, "dumpTables(): failed sanity check, could not find index (%s) for PK constraint\n",
B
Bruce Momjian 已提交
4125
								tblinfo[i].pkIndexOid);
4126 4127 4128 4129 4130
						exit_nicely(g_conn);
					}

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

B
Bruce Momjian 已提交
4131
					if ((actual_atts + tblinfo[i].ncheck) > 0)
4132
						appendPQExpBuffer(q, ",\n\t");
4133 4134 4135 4136

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

					destroyPQExpBuffer(consDef);
4137
				}
B
Bruce Momjian 已提交
4138

4139

4140
				appendPQExpBuffer(q, "\n)");
4141

4142
				if (numParents > 0)
B
Hi all  
Bruce Momjian 已提交
4143
				{
4144
					appendPQExpBuffer(q, "\nINHERITS (");
4145 4146 4147
					for (k = 0; k < numParents; k++)
					{
						appendPQExpBuffer(q, "%s%s",
B
Bruce Momjian 已提交
4148 4149
										  (k > 0) ? ", " : "",
									 fmtId(parentRels[k], force_quotes));
4150 4151
					}
					appendPQExpBuffer(q, ")");
B
Hi all  
Bruce Momjian 已提交
4152 4153
				}

4154 4155
				appendPQExpBuffer(q, ";\n");
			}
B
Bruce Momjian 已提交
4156

B
Bruce Momjian 已提交
4157 4158
			if (!dataOnly)
			{
4159

4160
				ArchiveEntry(fout, objoid, tblinfo[i].relname,
B
Bruce Momjian 已提交
4161 4162
							 reltypename, NULL, q->data, delq->data, "", tblinfo[i].usename,
							 NULL, NULL);
B
Bruce Momjian 已提交
4163

4164 4165 4166 4167
				if (!aclsSkip)
					dumpACL(fout, tblinfo[i]);

			}
4168

4169
			/* Dump Field Comments */
B
Bruce,  
Bruce Momjian 已提交
4170

4171 4172
			for (j = 0; j < tblinfo[i].numatts; j++)
			{
B
Bruce,  
Bruce Momjian 已提交
4173 4174 4175 4176 4177 4178
				resetPQExpBuffer(q);
				appendPQExpBuffer(q, "COLUMN %s", fmtId(tblinfo[i].relname, force_quotes));
				appendPQExpBuffer(q, ".");
				appendPQExpBuffer(q, "%s", fmtId(tblinfo[i].attnames[j], force_quotes));
				dumpComment(fout, q->data, tblinfo[i].attoids[j]);
			}
4179

B
Bruce,  
Bruce Momjian 已提交
4180
			/* Dump Table Comments */
4181

B
Bruce,  
Bruce Momjian 已提交
4182
			resetPQExpBuffer(q);
4183
			appendPQExpBuffer(q, "%s %s", reltypename, fmtId(tblinfo[i].relname, force_quotes));
B
Bruce,  
Bruce Momjian 已提交
4184
			dumpComment(fout, q->data, tblinfo[i].oid);
4185

4186 4187
		}
	}
4188 4189
}

B
Bruce Momjian 已提交
4190 4191
static PQExpBuffer
getPKconstraint(TableInfo *tblInfo, IndInfo *indInfo)
4192
{
B
Bruce Momjian 已提交
4193 4194
	PQExpBuffer pkBuf = createPQExpBuffer();
	int			k;
4195 4196

	appendPQExpBuffer(pkBuf, "Constraint %s Primary Key (",
B
Bruce Momjian 已提交
4197
					  tblInfo->primary_key_name);
4198 4199 4200

	for (k = 0; k < INDEX_MAX_KEYS; k++)
	{
4201 4202
		int			indkey;
		const char *attname;
4203 4204 4205 4206

		indkey = atoi(indInfo->indkey[k]);
		if (indkey == InvalidAttrNumber)
			break;
4207
		attname = getAttrName(indkey, tblInfo);
4208 4209

		appendPQExpBuffer(pkBuf, "%s%s",
B
Bruce Momjian 已提交
4210 4211
						  (k == 0) ? "" : ", ",
						  fmtId(attname, force_quotes));
4212 4213 4214 4215 4216 4217 4218
	}

	appendPQExpBuffer(pkBuf, ")");

	return pkBuf;
}

4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253
/*
 * 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";
	}
	fprintf(stderr, "getAttrName(): Invalid attribute number %d for table %s\n",
			attrnum, tblInfo->relname);
	exit_nicely(g_conn);
	return NULL;				/* keep compiler quiet */
}

4254 4255
/*
 * dumpIndices:
4256
 *	  write out to fout all the user-define indices
4257
 */
4258
void
B
Bruce Momjian 已提交
4259
dumpIndices(Archive *fout, IndInfo *indinfo, int numIndices,
4260
			TableInfo *tblinfo, int numTables, const char *tablename)
4261
{
4262 4263 4264
	int			i,
				k;
	int			tableInd;
4265
	PQExpBuffer attlist = createPQExpBuffer();
B
Bruce Momjian 已提交
4266 4267 4268
	char	   *classname[INDEX_MAX_KEYS];
	char	   *funcname;		/* the name of the function to comput the
								 * index key from */
4269
	int			indclass;
4270
	int			nclass;
4271

4272
	PQExpBuffer q = createPQExpBuffer(),
B
Bruce Momjian 已提交
4273
				delq = createPQExpBuffer(),
B
Hi, all  
Bruce Momjian 已提交
4274 4275
				id1 = createPQExpBuffer(),
				id2 = createPQExpBuffer();
4276
	PGresult   *res;
4277 4278 4279 4280

	for (i = 0; i < numIndices; i++)
	{
		tableInd = findTableByName(tblinfo, numTables,
4281 4282 4283
								   indinfo[i].indrelname);
		if (tableInd < 0)
		{
4284
			fprintf(stderr, "dumpIndices(): failed sanity check, table %s was not found\n",
4285
					indinfo[i].indrelname);
4286
			exit(1);
4287
		}
4288

4289 4290 4291 4292 4293 4294
		/* Handle PK indexes */
		if (strcmp(indinfo[i].indisprimary, "t") == 0)
		{
/*
 *			***PK: Enable this code when ALTER TABLE supports PK constraints. ***
 *
B
Bruce Momjian 已提交
4295
 *			PQExpBuffer consDef = getPKconstraint(&tblinfo[tableInd], &indinfo[i]);
4296 4297 4298
 *
 *			resetPQExpBuffer(attlist);
 *
B
Bruce Momjian 已提交
4299
 *			appendPQExpBuffer(attlist, "Alter Table %s Add %s;",
4300 4301 4302
 *								fmtId(tblinfo[tableInd].relname, force_quotes),
 *								consDef->data);
 *
B
Bruce Momjian 已提交
4303
 *			ArchiveEntry(fout, indinfo[i].oid, tblinfo[tableInd].primary_key_name, "CONSTRAINT", NULL,
4304 4305 4306 4307 4308
 *							attlist->data, "",
 *							"", tblinfo[tableInd].usename, NULL, NULL);
 *
 *			destroyPQExpBuffer(consDef);
 */
B
Bruce Momjian 已提交
4309 4310 4311 4312 4313

			/*
			 * Don't need to do anything else for this system-generated
			 * index
			 */
4314 4315 4316 4317
			continue;
		}


4318 4319 4320 4321
		if (strcmp(indinfo[i].indproc, "0") == 0)
			funcname = NULL;
		else
		{
B
Bruce Momjian 已提交
4322
			int			numFuncs;
4323 4324 4325 4326 4327 4328 4329

			/*
			 * the funcname is an oid which we use to find the name of the
			 * pg_proc.  We need to do this because getFuncs() only reads
			 * in the user-defined funcs not all the funcs.  We might not
			 * find what we want by looking in FuncInfo*
			 */
B
Hi, all  
Bruce Momjian 已提交
4330 4331
			resetPQExpBuffer(q);
			appendPQExpBuffer(q,
4332 4333 4334
							  "SELECT proname from pg_proc "
							  "where pg_proc.oid = '%s'::oid",
							  indinfo[i].indproc);
B
Hi, all  
Bruce Momjian 已提交
4335
			res = PQexec(g_conn, q->data);
4336 4337
			if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
			{
B
Bruce Momjian 已提交
4338 4339
				fprintf(stderr, "dumpIndices(): SELECT (funcname) failed.  "
						"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
4340 4341
				exit_nicely(g_conn);
			}
4342 4343 4344

			/* Sanity: Check we got only one tuple */
			numFuncs = PQntuples(res);
B
Bruce Momjian 已提交
4345 4346 4347 4348
			if (numFuncs != 1)
			{
				fprintf(stderr, "dumpIndices(): SELECT (funcname) for index %s returned %d tuples. Expected 1.\n",
						indinfo[i].indrelname, numFuncs);
4349 4350 4351
				exit_nicely(g_conn);
			}

B
Bruce Momjian 已提交
4352
			funcname = strdup(PQgetvalue(res, 0, PQfnumber(res, "proname")));
4353 4354 4355 4356 4357 4358
			PQclear(res);
		}

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

4361 4362 4363
			indclass = atoi(indinfo[i].indclass[nclass]);
			if (indclass == 0)
				break;
B
Hi, all  
Bruce Momjian 已提交
4364 4365
			resetPQExpBuffer(q);
			appendPQExpBuffer(q,
4366 4367 4368
							  "SELECT opcname from pg_opclass "
							  "where pg_opclass.oid = '%u'::oid",
							  indclass);
B
Hi, all  
Bruce Momjian 已提交
4369
			res = PQexec(g_conn, q->data);
4370 4371
			if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
			{
B
Bruce Momjian 已提交
4372
				fprintf(stderr, "dumpIndices(): SELECT (classname) failed.  "
B
Bruce Momjian 已提交
4373
						"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
4374 4375
				exit_nicely(g_conn);
			}
4376 4377 4378

			/* Sanity: Check we got only one tuple */
			numRows = PQntuples(res);
B
Bruce Momjian 已提交
4379 4380 4381 4382
			if (numRows != 1)
			{
				fprintf(stderr, "dumpIndices(): SELECT (classname) for index %s returned %d tuples. Expected 1.\n",
						indinfo[i].indrelname, numRows);
4383 4384 4385
				exit_nicely(g_conn);
			}

B
Bruce Momjian 已提交
4386
			classname[nclass] = strdup(PQgetvalue(res, 0, PQfnumber(res, "opcname")));
4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397
			PQclear(res);
		}

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

		/* convert attribute numbers into attribute list */
B
Hi, all  
Bruce Momjian 已提交
4398 4399
		resetPQExpBuffer(attlist);
		for (k = 0; k < INDEX_MAX_KEYS; k++)
4400
		{
4401 4402
			int			indkey;
			const char *attname;
4403 4404

			indkey = atoi(indinfo[i].indkey[k]);
B
Bruce Momjian 已提交
4405
			if (indkey == InvalidAttrNumber)
4406
				break;
4407
			attname = getAttrName(indkey, &tblinfo[tableInd]);
4408
			if (funcname)
B
Hi, all  
Bruce Momjian 已提交
4409
				appendPQExpBuffer(attlist, "%s%s",
4410 4411
								  (k == 0) ? "" : ", ",
								  fmtId(attname, force_quotes));
4412 4413 4414 4415 4416
			else
			{
				if (k >= nclass)
				{
					fprintf(stderr, "dumpIndices(): OpClass not found for "
4417
							"attribute '%s' of index '%s'\n",
4418 4419 4420
							attname, indinfo[i].indexrelname);
					exit_nicely(g_conn);
				}
B
Hi, all  
Bruce Momjian 已提交
4421 4422 4423 4424 4425
				resetPQExpBuffer(id1);
				resetPQExpBuffer(id2);
				appendPQExpBuffer(id1, fmtId(attname, force_quotes));
				appendPQExpBuffer(id2, fmtId(classname[k], force_quotes));
				appendPQExpBuffer(attlist, "%s%s %s",
4426 4427
								  (k == 0) ? "" : ", ",
								  id1->data, id2->data);
4428 4429 4430 4431
				free(classname[k]);
			}
		}

B
Bruce Momjian 已提交
4432
		if (!tablename || (strcmp(indinfo[i].indrelname, tablename) == 0) || (strlen(tablename) == 0))
4433
		{
B
Hi, all  
Bruce Momjian 已提交
4434 4435 4436 4437
			resetPQExpBuffer(id1);
			resetPQExpBuffer(id2);
			appendPQExpBuffer(id1, fmtId(indinfo[i].indexrelname, force_quotes));
			appendPQExpBuffer(id2, fmtId(indinfo[i].indrelname, force_quotes));
4438

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

B
Bruce Momjian 已提交
4442 4443
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "CREATE %s INDEX %s on %s using %s (",
B
Bruce Momjian 已提交
4444 4445 4446 4447
			  (strcmp(indinfo[i].indisunique, "t") == 0) ? "UNIQUE" : "",
							  id1->data,
							  id2->data,
							  indinfo[i].indamname);
4448 4449
			if (funcname)
			{
4450
				/* need 2 printf's here cuz fmtId has static return area */
B
Bruce Momjian 已提交
4451
				appendPQExpBuffer(q, " %s", fmtId(funcname, false));
B
Bruce Momjian 已提交
4452 4453
				appendPQExpBuffer(q, " (%s) %s );\n", attlist->data,
								  fmtId(classname[0], force_quotes));
4454 4455 4456 4457
				free(funcname);
				free(classname[0]);
			}
			else
B
Bruce Momjian 已提交
4458
				appendPQExpBuffer(q, " %s );\n", attlist->data);
B
Bruce,  
Bruce Momjian 已提交
4459

4460 4461 4462 4463 4464
			/*
			 * 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.
			 */
B
Bruce Momjian 已提交
4465
			ArchiveEntry(fout, tblinfo[tableInd].oid, id1->data, "INDEX", NULL, q->data, delq->data,
B
Bruce Momjian 已提交
4466
						 "", tblinfo[tableInd].usename, NULL, NULL);
B
Bruce Momjian 已提交
4467

4468
			/* Dump Index Comments */
B
Bruce,  
Bruce Momjian 已提交
4469 4470 4471
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "INDEX %s", id1->data);
			dumpComment(fout, q->data, indinfo[i].indoid);
4472

4473 4474
		}
	}
4475 4476

}
4477

4478
/*
B
Bruce Momjian 已提交
4479
 * dumpTuples
4480 4481 4482 4483 4484
 *	  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
4485
 *	  in PostgreSQL.
4486 4487 4488 4489
 *
 * the attrmap passed in tells how to map the attributes copied in to the
 * attributes copied out
 */
4490
#ifdef NOT_USED
4491
void
4492
dumpTuples(PGresult *res, FILE *fout, int *attrmap)
4493
{
4494 4495 4496 4497
	int			j,
				k;
	int			m,
				n;
B
Bruce Momjian 已提交
4498
	char	  **outVals = NULL; /* values to copy out */
4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517

	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++)
			{
4518
				char	   *pval = outVals[k];
4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538

				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);
	}
4539
}
4540

4541
#endif
4542

4543 4544 4545 4546
/*
 * setMaxOid -
 * find the maximum oid and generate a COPY statement to set it
*/
4547

4548
static void
B
Bruce Momjian 已提交
4549
setMaxOid(Archive *fout)
4550
{
B
Bruce Momjian 已提交
4551 4552
	PGresult   *res;
	Oid			max_oid;
B
Bruce Momjian 已提交
4553
	char		sql[1024];
B
Bruce Momjian 已提交
4554
	int			pos;
4555

4556
	res = PQexec(g_conn, "CREATE TEMPORARY TABLE pgdump_oid (dummy int4)");
4557 4558 4559
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
4560
		fprintf(stderr, "Can not create pgdump_oid table.  "
B
Bruce Momjian 已提交
4561
			"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
4562 4563 4564
		exit_nicely(g_conn);
	}
	PQclear(res);
4565
	res = PQexec(g_conn, "INSERT INTO pgdump_oid VALUES (0)");
4566 4567 4568
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
4569
		fprintf(stderr, "Can not insert into pgdump_oid table.  "
B
Bruce Momjian 已提交
4570
			"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
4571 4572 4573 4574 4575 4576 4577 4578 4579
		exit_nicely(g_conn);
	}
	max_oid = atol(PQoidStatus(res));
	if (max_oid == 0)
	{
		fprintf(stderr, "Invalid max id in setMaxOid\n");
		exit_nicely(g_conn);
	}
	PQclear(res);
4580
	res = PQexec(g_conn, "DROP TABLE pgdump_oid;");
4581 4582 4583
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
4584
		fprintf(stderr, "Can not drop pgdump_oid table.  "
B
Bruce Momjian 已提交
4585
			"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
4586 4587 4588 4589
		exit_nicely(g_conn);
	}
	PQclear(res);
	if (g_verbose)
4590
		fprintf(stderr, "%s maximum system oid is %u %s\n",
4591
				g_comment_start, max_oid, g_comment_end);
4592
	pos = snprintf(sql, 1024, "CREATE TEMPORARY TABLE pgdump_oid (dummy int4);\n");
B
Bruce Momjian 已提交
4593 4594 4595 4596
	pos = pos + snprintf(sql + pos, 1024 - pos, "COPY pgdump_oid WITH OIDS FROM stdin;\n");
	pos = pos + snprintf(sql + pos, 1024 - pos, "%-d\t0\n", max_oid);
	pos = pos + snprintf(sql + pos, 1024 - pos, "\\.\n");
	pos = pos + snprintf(sql + pos, 1024 - pos, "DROP TABLE pgdump_oid;\n");
B
Bruce Momjian 已提交
4597

4598
	ArchiveEntry(fout, "0", "Max OID", "<Init>", NULL, sql, "", "", "", NULL, NULL);
4599
}
4600 4601 4602

/*
 * findLastBuiltInOid -
4603
 * find the last built in oid
4604 4605
 * we do this by retrieving datlastsysoid from the pg_database entry for this database,
 */
4606

4607
static Oid
4608
findLastBuiltinOid_V71(const char *dbname)
4609
{
B
Bruce Momjian 已提交
4610
	PGresult   *res;
4611
	int			ntups;
4612
	Oid			last_oid;
4613 4614 4615
	PQExpBuffer query = createPQExpBuffer();

	resetPQExpBuffer(query);
4616
	appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
4617
	formatStringLiteral(query, dbname, CONV_ALL);
4618

4619
	res = PQexec(g_conn, query->data);
4620 4621 4622
	if (res == NULL ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
4623
		fprintf(stderr, "pg_dump: error in finding the last system OID. ");
4624
		fprintf(stderr, "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
4625 4626 4627
		exit_nicely(g_conn);
	}
	ntups = PQntuples(res);
4628
	if (ntups < 1)
4629
	{
4630 4631
		fprintf(stderr, "pg_dump: couldn't find the pg_database entry.\n");
		fprintf(stderr, "There is no entry in the 'pg_database' table for this database.\n");
4632 4633 4634 4635
		exit_nicely(g_conn);
	}
	if (ntups > 1)
	{
4636 4637
		fprintf(stderr, "pg_dump: found more than one matching database.\n");
		fprintf(stderr, "There is more than one entry for this database in the 'pg_database' table\n");
4638 4639
		exit_nicely(g_conn);
	}
4640
	last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
4641 4642
	PQclear(res);
	return last_oid;
4643 4644
}

4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684
/*
 * 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
*/

static Oid 
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)
	{
		fprintf(stderr, "pg_dump error in finding the template1 database.");
		fprintf(stderr, "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
		exit_nicely(g_conn);
	}
	ntups = PQntuples(res);
	if (ntups < 1)
	{
		fprintf(stderr, "pg_dump: couldn't find the template1 database.\n");
		fprintf(stderr, "There is no 'template1' entry in the 'pg_database' table.\n");
		exit_nicely(g_conn);
	}
	if (ntups > 1)
	{
		fprintf(stderr, "pg_dump: found more than one template1 database.\n");
		fprintf(stderr, "There is more than one 'template1' entry in the 'pg_database' table\n");
		exit_nicely(g_conn);
	}
	last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
	PQclear(res);
	return last_oid;
}
4685

4686
static void
4687
dumpSequence(Archive *fout, TableInfo tbinfo, const bool schemaOnly, const bool dataOnly)
4688
{
4689
	PGresult   *res;
B
Bruce Momjian 已提交
4690
	int4		last,
4691 4692 4693 4694
				incby,
				maxv,
				minv,
				cache;
B
Bruce Momjian 已提交
4695
	char		cycled,
B
Bruce Momjian 已提交
4696
				called;
4697 4698
	const char *t;
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
4699
	PQExpBuffer delqry = createPQExpBuffer();
4700

B
Hi, all  
Bruce Momjian 已提交
4701
	appendPQExpBuffer(query,
4702
			"SELECT sequence_name, last_value, increment_by, max_value, "
4703 4704
				  "min_value, cache_value, is_cycled, is_called from %s",
					  fmtId(tbinfo.relname, force_quotes));
4705

B
Hi, all  
Bruce Momjian 已提交
4706
	res = PQexec(g_conn, query->data);
4707 4708
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
4709
		fprintf(stderr, "dumpSequence(%s): SELECT failed.  "
B
Bruce Momjian 已提交
4710
				"Explanation from backend: '%s'.\n", tbinfo.relname, PQerrorMessage(g_conn));
4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739
		exit_nicely(g_conn);
	}

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

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


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

4740
	/*
B
Bruce Momjian 已提交
4741 4742
	 * The logic we use for restoring sequences is as follows: -   Add a
	 * basic CREATE SEQUENCE statement (use last_val for start if called
4743 4744 4745 4746
	 * with 'f', else use min_val for start_val).
	 *
	 *	Add a 'SETVAL(seq, last_val, iscalled)' at restore-time iff
	 *  we load data
4747
	 */
4748

4749 4750 4751
	if (!dataOnly)
	{
		PQclear(res);
4752

4753 4754
		resetPQExpBuffer(delqry);
		appendPQExpBuffer(delqry, "DROP SEQUENCE %s;\n", fmtId(tbinfo.relname, force_quotes));
4755

4756 4757
		resetPQExpBuffer(query);
		appendPQExpBuffer(query,
B
Bruce Momjian 已提交
4758
				  "CREATE SEQUENCE %s start %d increment %d maxvalue %d "
4759
						  "minvalue %d  cache %d %s;\n",
B
Bruce Momjian 已提交
4760
						  fmtId(tbinfo.relname, force_quotes),
4761 4762 4763 4764
						  (called == 't') ? minv : last,
						  incby, maxv, minv, cache,
						  (cycled == 't') ? "cycle" : "");

P
Philip Warner 已提交
4765
		ArchiveEntry(fout, tbinfo.oid, tbinfo.relname, "SEQUENCE", NULL,
B
Bruce Momjian 已提交
4766
			  query->data, delqry->data, "", tbinfo.usename, NULL, NULL);
4767
	}
4768

4769 4770 4771 4772 4773 4774
	if (!schemaOnly)
	{
		resetPQExpBuffer(query);
		appendPQExpBuffer(query, "SELECT setval (");
		formatStringLiteral(query, fmtId(tbinfo.relname, force_quotes), CONV_ALL);
		appendPQExpBuffer(query, ", %d, '%c');\n", last, called);
4775

P
Philip Warner 已提交
4776
		ArchiveEntry(fout, tbinfo.oid, tbinfo.relname, "SEQUENCE SET", NULL,
B
Bruce Momjian 已提交
4777
					 query->data, "" /* Del */ , "", "", NULL, NULL);
4778
	}
B
Bruce,  
Bruce Momjian 已提交
4779

4780 4781 4782
	if (!dataOnly)
	{
		/* Dump Sequence Comments */
B
Bruce,  
Bruce Momjian 已提交
4783

4784 4785 4786 4787
		resetPQExpBuffer(query);
		appendPQExpBuffer(query, "SEQUENCE %s", fmtId(tbinfo.relname, force_quotes));
		dumpComment(fout, query->data, tbinfo.oid);
	}
4788
}
V
Vadim B. Mikheev 已提交
4789 4790


4791
static void
B
Bruce Momjian 已提交
4792
dumpTriggers(Archive *fout, const char *tablename,
4793
			 TableInfo *tblinfo, int numTables)
V
Vadim B. Mikheev 已提交
4794
{
4795 4796 4797
	int			i,
				j;

V
Vadim B. Mikheev 已提交
4798 4799 4800
	if (g_verbose)
		fprintf(stderr, "%s dumping out triggers %s\n",
				g_comment_start, g_comment_end);
4801

V
Vadim B. Mikheev 已提交
4802 4803
	for (i = 0; i < numTables; i++)
	{
B
Bruce Momjian 已提交
4804
		if (tablename && (strcmp(tblinfo[i].relname, tablename) != 0) && (strlen(tablename) > 0))
V
Vadim B. Mikheev 已提交
4805
			continue;
4806

V
Vadim B. Mikheev 已提交
4807 4808
		for (j = 0; j < tblinfo[i].ntrig; j++)
		{
B
Bruce Momjian 已提交
4809
			ArchiveEntry(fout, tblinfo[i].triggers[j].oid, tblinfo[i].triggers[j].tgname,
B
Bruce Momjian 已提交
4810 4811
				   "TRIGGER", NULL, tblinfo[i].triggers[j].tgsrc, "", "",
						 tblinfo[i].usename, NULL, NULL);
B
Bruce Momjian 已提交
4812
			dumpComment(fout, tblinfo[i].triggers[j].tgcomment, tblinfo[i].triggers[j].oid);
V
Vadim B. Mikheev 已提交
4813 4814 4815
		}
	}
}
4816 4817


4818
static void
B
Bruce Momjian 已提交
4819
dumpRules(Archive *fout, const char *tablename,
B
Bruce Momjian 已提交
4820
		  TableInfo *tblinfo, int numTables)
4821
{
B
Bruce Momjian 已提交
4822 4823 4824 4825
	PGresult   *res;
	int			nrules;
	int			i,
				t;
4826
	PQExpBuffer query = createPQExpBuffer();
4827

B
Bruce Momjian 已提交
4828
	int			i_definition;
4829
	int			i_oid;
4830
	int			i_owner;
4831
	int			i_rulename;
4832 4833 4834 4835 4836 4837 4838 4839 4840 4841

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

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

		/*
B
Bruce Momjian 已提交
4846 4847
		 * 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).
4848 4849
		 *
		 * XXXX: Use LOJ here
4850
		 */
B
Hi, all  
Bruce Momjian 已提交
4851
		resetPQExpBuffer(query);
4852
		appendPQExpBuffer(query, "SELECT definition,"
4853
						  "   (select usename from pg_user where pg_class.relowner = usesysid) AS viewowner, "
4854 4855
						  "   pg_rewrite.oid, pg_rewrite.rulename "
						  "FROM pg_rewrite, pg_class, pg_rules "
4856
						  "WHERE pg_class.relname = ");
4857
		formatStringLiteral(query, tblinfo[t].relname, CONV_ALL);
4858
		appendPQExpBuffer(query,
4859 4860
						  "    AND pg_rewrite.ev_class = pg_class.oid "
						  "    AND pg_rules.tablename = pg_class.relname "
B
Bruce Momjian 已提交
4861
					   "    AND pg_rules.rulename = pg_rewrite.rulename "
4862
						  "ORDER BY pg_rewrite.oid");
B
Hi, all  
Bruce Momjian 已提交
4863
		res = PQexec(g_conn, query->data);
4864 4865 4866
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
4867
			fprintf(stderr, "dumpRules(): SELECT failed for rules associated with table \"%s\".\n\tExplanation from backend: '%s'.\n",
B
Bruce Momjian 已提交
4868
					tblinfo[t].relname, PQerrorMessage(g_conn));
4869 4870 4871 4872 4873
			exit_nicely(g_conn);
		}

		nrules = PQntuples(res);
		i_definition = PQfnumber(res, "definition");
4874
		i_owner = PQfnumber(res, "viewowner");
B
Bruce,  
Bruce Momjian 已提交
4875 4876
		i_oid = PQfnumber(res, "oid");
		i_rulename = PQfnumber(res, "rulename");
4877 4878 4879 4880

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

4882 4883
		for (i = 0; i < nrules; i++)
		{
B
Bruce Momjian 已提交
4884
			ArchiveEntry(fout, PQgetvalue(res, i, i_oid), PQgetvalue(res, i, i_rulename),
B
Bruce Momjian 已提交
4885 4886
						 "RULE", NULL, PQgetvalue(res, i, i_definition),
						 "", "", PQgetvalue(res, i, i_owner), NULL, NULL);
4887

B
Bruce,  
Bruce Momjian 已提交
4888 4889 4890 4891 4892
			/* Dump rule comments */

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

B
Bruce,  
Bruce Momjian 已提交
4894 4895
		}

4896 4897 4898
		PQclear(res);
	}
}