pg_dump.c 131.2 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * pg_dump.c
4
 *	  pg_dump is a utility for dumping out a postgres database
B
Bruce Momjian 已提交
5
 *	  into a script file.
6 7 8
 *
 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
9
 *
10 11 12 13 14 15 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.206 2001/05/12 01:03:59 pjw 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 270 271 272 273
	"  -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"
		 "  -u, --password           use password authentication\n"
		 "  -v, --verbose            verbose\n"
		 "  -x, --no-acl             do not dump ACL's (grant/revoke)\n"
		 "  -Z, --compress {0-9}     compression level for compressed formats\n"
274
		);
B
Hi,  
Bruce Momjian 已提交
275
#else
276
	puts(
B
Bruce Momjian 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
		 "  -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"
		 "  -u                       use password authentication\n"
		 "  -v                       verbose\n"
		 "  -x                       do not dump ACL's (grant/revoke)\n"
		 "  -Z {0-9}                 compression level for compressed formats\n"
303
		);
B
Hi,  
Bruce Momjian 已提交
304
#endif
305 306
	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>.");
307
}
308

309

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

319

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


328 329
#define COPYBUFSIZ		8192

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

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

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

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

352
	if (oids == true)
353
	{
B
Bruce Momjian 已提交
354 355

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

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

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

377
		sprintf(query, "COPY %s TO stdout;\n", fmtId(classname, force_quotes));
378 379
	}
	res = PQexec(g_conn, query);
380 381
	if (!res ||
		PQresultStatus(res) == PGRES_FATAL_ERROR)
382
	{
383
		fprintf(stderr, "SQL query to dump the contents of Table '%s' "
384 385 386 387 388 389 390 391 392
				"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)
		{
393
			fprintf(stderr, "SQL query to dump the contents of Table '%s' "
394 395 396 397 398 399 400 401 402
					"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;
403

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

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

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

B
Bruce Momjian 已提交
491
	return 1;
492 493
}

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

B
Bruce Momjian 已提交
729
	RestoreOptions *ropt;
730

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

B
Hi,  
Bruce Momjian 已提交
761 762
#endif

763
	g_verbose = false;
764
	force_quotes = true;
765 766 767 768 769

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

770
	dataOnly = schemaOnly = dumpData = attrNames = false;
771

772 773 774 775
	if (!strrchr(argv[0], SEP_CHAR))
		progname = argv[0];
	else
		progname = strrchr(argv[0], SEP_CHAR) + 1;
776

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

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

B
Hi,  
Bruce Momjian 已提交
798
#ifdef HAVE_GETOPT_LONG
799
	while ((c = getopt_long(argc, argv, "abcCdDf:F:h:inNoOp:RsS:t:uvxzZ:V?", long_options, &optindex)) != -1)
B
Hi,  
Bruce Momjian 已提交
800
#else
801
	while ((c = getopt(argc, argv, "abcCdDf:F:h:inNoOp:RsS:t:uvxzZ:V?-")) != -1)
B
Hi,  
Bruce Momjian 已提交
802
#endif
803

804 805 806
	{
		switch (c)
		{
807
			case 'a':			/* Dump data only */
808
				dataOnly = true;
809
				break;
810

811 812 813 814
			case 'b':			/* Dump blobs */
				outputBlobs = true;
				break;

B
Bruce Momjian 已提交
815
			case 'c':			/* clean (i.e., drop) schema prior to
B
Bruce Momjian 已提交
816
								 * create */
B
Bruce Momjian 已提交
817
				outputClean = 1;
B
Bruce Momjian 已提交
818 819
				break;

820 821 822 823 824
			case 'C':			/* Create DB */

				outputCreate = 1;
				break;

825
			case 'd':			/* dump data as proper insert strings */
826
				dumpData = true;
827
				break;
828

829 830
			case 'D':			/* dump data as proper insert strings with
								 * attr names */
831 832
				dumpData = true;
				attrNames = true;
833
				break;
834

835
			case 'f':
836 837
				filename = optarg;
				break;
838

B
Bruce Momjian 已提交
839 840 841
			case 'F':
				format = optarg;
				break;
842

B
Bruce Momjian 已提交
843
			case 'h':			/* server host */
844 845
				pghost = optarg;
				break;
846

847 848 849
			case 'i':			/* ignore database version mismatch */
				ignore_version = true;
				break;
850

B
Bruce Momjian 已提交
851 852
			case 'n':			/* Do not force double-quotes on
								 * identifiers */
853
				force_quotes = false;
854
				break;
855

856
			case 'N':			/* Force double-quotes on identifiers */
857
				force_quotes = true;
858
				break;
859

860
			case 'o':			/* Dump oids */
861
				oids = true;
862
				break;
863 864


865 866 867
			case 'O':			/* Don't reconnect to match owner */
				outputNoOwner = 1;
				break;
868

869 870 871
			case 'p':			/* server port */
				pgport = optarg;
				break;
872

873 874 875
			case 'R':			/* No reconnect */
				outputNoReconnect = 1;
				break;
876

877
			case 's':			/* dump schema only */
878
				schemaOnly = true;
879
				break;
880

B
Bruce Momjian 已提交
881 882
			case 'S':			/* Username for superuser in plain text
								 * output */
883 884
				outputSuperuser = strdup(optarg);
				break;
885

886
			case 't':			/* Dump data for this table only */
887
				{
888
					int			i;
889 890

					tablename = strdup(optarg);
B
Bruce Momjian 已提交
891 892 893 894 895

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

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

916
					}
917
				}
918
				break;
919

920 921 922
			case 'u':
				use_password = true;
				break;
923

924 925
			case 'v':			/* verbose */
				g_verbose = true;
926
				break;
927

928 929
			case 'x':			/* skip ACL dump */
				aclsSkip = true;
930
				break;
931

B
Bruce Momjian 已提交
932 933 934
			case 'Z':			/* Compression Level */
				compressLevel = atoi(optarg);
				break;
935

936 937 938 939
			case 'V':
				version();
				exit(0);
				break;
940

941 942 943
#ifndef HAVE_GETOPT_LONG
			case '-':
				fprintf(stderr, "%s was compiled without support for long options.\n"
B
Bruce Momjian 已提交
944
				"Use --help for help on invocation options.\n", progname);
945 946 947
				exit(1);
				break;
#endif
948
			default:
949
				fprintf(stderr, "Try '%s --help' for more information.\n", progname);
950
				exit(1);
951 952 953
		}
	}

B
Bruce Momjian 已提交
954 955
	if (optind < (argc - 1))
	{
P
Philip Warner 已提交
956 957
		fprintf(stderr,
				"%s: extra parameters found on command line after '%s' (first is '%s').\n"
B
Bruce Momjian 已提交
958 959
				"Please respecify command.\nUse --help for help on invocation options.\n",
				progname, argv[optind], argv[optind + 1]);
P
Philip Warner 已提交
960 961 962
		exit(1);
	}

963 964 965 966 967 968 969 970 971 972 973 974 975
	/* 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 已提交
976 977 978
	if (dataOnly && schemaOnly)
	{
		fprintf(stderr,
B
Bruce Momjian 已提交
979
		 "%s: 'Schema Only' and 'Data Only' are incompatible options.\n",
B
Bruce Momjian 已提交
980 981 982 983
				progname);
		exit(1);
	}

B
Bruce Momjian 已提交
984
	if (outputBlobs && tablename != NULL && strlen(tablename) > 0)
985 986
	{
		fprintf(stderr,
987
				"%s: BLOB output is not supported for a single table. Use all tables or a full dump instead.\n",
988 989 990 991
				progname);
		exit(1);
	}

992 993 994
	if (dumpData == true && oids == true)
	{
		fprintf(stderr,
995
				"%s: INSERT's can not set oids, so INSERT and OID options can not be used together.\n",
996
				progname);
997
		exit(1);
998
	}
999

B
Bruce Momjian 已提交
1000
	if (outputBlobs == true && (format[0] == 'p' || format[0] == 'P'))
P
Philip Warner 已提交
1001 1002
	{
		fprintf(stderr,
B
Bruce Momjian 已提交
1003 1004
				"%s: BLOB output is not supported for plain text dump files. Use a different output format.\n",
				progname);
P
Philip Warner 已提交
1005 1006 1007
		exit(1);
	}

1008
	/* open the output file */
B
Bruce Momjian 已提交
1009 1010
	switch (format[0])
	{
B
Bruce Momjian 已提交
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024

		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;
1025 1026 1027 1028 1029 1030
			g_fout = CreateArchive(filename, archNull, 0);
			break;

		case 't':
		case 'T':
			g_fout = CreateArchive(filename, archTar, compressLevel);
B
Bruce Momjian 已提交
1031 1032 1033
			break;

		default:
1034
			fprintf(stderr,
B
Bruce Momjian 已提交
1035 1036
					"%s: invalid output format '%s' specified\n", progname, format);
			exit(1);
B
Bruce Momjian 已提交
1037 1038 1039 1040 1041
	}

	if (g_fout == NULL)
	{
		fprintf(stderr,
B
Bruce Momjian 已提交
1042
				"%s: could not open output file named %s for writing\n",
B
Bruce Momjian 已提交
1043 1044
				progname, filename);
		exit(1);
1045 1046
	}

1047 1048
	/* Let the archiver know how noisy to be */
	g_fout->verbose = g_verbose;
1049

B
Bruce Momjian 已提交
1050 1051
	/*
	 * Open the database using the Archiver, so it knows about it. Errors
1052
	 * mean death. Accept 7.0 & 7.1 database versions.
B
Bruce Momjian 已提交
1053
	 */
1054 1055
	g_fout->minRemoteVersion = 70000;
	g_fout->maxRemoteVersion = 70199;
1056
	g_conn = ConnectDatabase(g_fout, dbname, pghost, pgport, use_password, ignore_version);
1057

1058 1059 1060 1061 1062 1063 1064 1065
	/*
	 * Start serializable transaction to dump consistent data
	 */
	{
		PGresult   *res;

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

1069 1070 1071
		PQclear(res);
		res = PQexec(g_conn, "set transaction isolation level serializable");
		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
B
Bruce Momjian 已提交
1072 1073
			exit_horribly(g_fout, "SET TRANSACTION command failed. Explanation from backend: '%s'.\n",
						  PQerrorMessage(g_conn));
1074

1075 1076 1077
		PQclear(res);
	}

1078 1079 1080 1081
	if (g_fout->remoteVersion >= 70100)
		g_last_builtin_oid = findLastBuiltinOid_V71(dbname);
	else
		g_last_builtin_oid = findLastBuiltinOid_V70();
1082

1083 1084 1085 1086
	/* Dump the database definition */
	if (!dataOnly)
		dumpDatabase(g_fout);

1087
	if (oids == true)
1088
		setMaxOid(g_fout);
B
Bruce Momjian 已提交
1089 1090

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

1095
	if (!schemaOnly)
B
Bruce Momjian 已提交
1096
		dumpClasses(tblinfo, numTables, g_fout, tablename, oids, force_quotes);
1097 1098

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

1101 1102
	if (!dataOnly)				/* dump indexes and triggers at the end
								 * for performance */
V
Vadim B. Mikheev 已提交
1103 1104
	{
		dumpTriggers(g_fout, tablename, tblinfo, numTables);
1105
		dumpRules(g_fout, tablename, tblinfo, numTables);
V
Vadim B. Mikheev 已提交
1106
	}
1107

1108 1109
	/* Now sort the output nicely */
	SortTocByOID(g_fout);
1110
	MoveToStart(g_fout, "DATABASE");
1111 1112 1113
	MoveToEnd(g_fout, "TABLE DATA");
	MoveToEnd(g_fout, "BLOBS");
	MoveToEnd(g_fout, "INDEX");
1114
	MoveToEnd(g_fout, "CONSTRAINT");
1115 1116
	MoveToEnd(g_fout, "TRIGGER");
	MoveToEnd(g_fout, "RULE");
1117
	MoveToEnd(g_fout, "SEQUENCE SET");
1118

B
Bruce Momjian 已提交
1119
	if (plainText)
B
Bruce Momjian 已提交
1120 1121
	{
		ropt = NewRestoreOptions();
B
Bruce Momjian 已提交
1122
		ropt->filename = (char *) filename;
B
Bruce Momjian 已提交
1123 1124
		ropt->dropSchema = outputClean;
		ropt->aclsSkip = aclsSkip;
1125 1126 1127 1128 1129 1130 1131 1132 1133
		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 已提交
1134 1135

		if (compressLevel == -1)
B
Bruce Momjian 已提交
1136
			ropt->compression = 0;
B
Bruce Momjian 已提交
1137
		else
B
Bruce Momjian 已提交
1138
			ropt->compression = compressLevel;
B
Bruce Momjian 已提交
1139

1140 1141
		ropt->suppressDumpWarnings = true; /* We've already shown them */

B
Bruce Momjian 已提交
1142 1143 1144 1145
		RestoreArchive(g_fout, ropt);
	}

	CloseArchive(g_fout);
1146

1147 1148 1149
	clearTableInfo(tblinfo, numTables);
	PQfinish(g_conn);
	exit(0);
1150 1151
}

1152 1153 1154 1155 1156
/*
 * dumpDatabase:
 *	dump the database definition
 *
 */
B
Bruce Momjian 已提交
1157
static int
1158 1159
dumpDatabase(Archive *AH)
{
B
Bruce Momjian 已提交
1160 1161 1162 1163 1164 1165
	PQExpBuffer dbQry = createPQExpBuffer();
	PQExpBuffer delQry = createPQExpBuffer();
	PQExpBuffer creaQry = createPQExpBuffer();
	PGresult   *res;
	int			ntups;
	int			i_dba;
1166 1167 1168 1169 1170

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

	/* Get the dba */
1171
	appendPQExpBuffer(dbQry, "select (select usename from pg_user where datdba = usesysid) as dba from pg_database"
B
Bruce Momjian 已提交
1172
					  " where datname = ");
1173
	formatStringLiteral(dbQry, PQdb(g_conn), CONV_ALL);
1174 1175 1176 1177 1178

	res = PQexec(g_conn, dbQry->data);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
1179 1180
		fprintf(stderr, "getDatabase(): SELECT failed.  Explanation from backend: '%s'.\n",
				PQerrorMessage(g_conn));
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
		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 已提交
1196 1197 1198 1199
	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 */ );
1200 1201 1202 1203 1204 1205 1206

	PQclear(res);

	return 1;
}


1207 1208 1209 1210 1211 1212
/*
 * dumpBlobs:
 *	dump all blobs
 *
 */

B
Bruce Momjian 已提交
1213
#define loBufSize 16384
1214 1215
#define loFetchSize 1000

B
Bruce Momjian 已提交
1216 1217
static int
dumpBlobs(Archive *AH, char *junkOid, void *junkVal)
1218
{
B
Bruce Momjian 已提交
1219 1220 1221 1222 1223 1224 1225 1226
	PQExpBuffer oidQry = createPQExpBuffer();
	PQExpBuffer oidFetchQry = createPQExpBuffer();
	PGresult   *res;
	int			i;
	int			loFd;
	char		buf[loBufSize];
	int			cnt;
	int			blobOid;
1227 1228 1229 1230 1231

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

	/* Cursor to get all BLOB tables */
1232 1233 1234 1235 1236 1237
	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'");
	}
1238 1239 1240 1241

	res = PQexec(g_conn, oidQry->data);
	if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
	{
B
Bruce Momjian 已提交
1242 1243
		fprintf(stderr, "dumpBlobs(): Declare Cursor failed.  Explanation from backend: '%s'.\n",
				PQerrorMessage(g_conn));
1244 1245 1246 1247 1248 1249
		exit_nicely(g_conn);
	}

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

B
Bruce Momjian 已提交
1250 1251
	do
	{
1252 1253 1254 1255 1256 1257
		/* Do a fetch */
		PQclear(res);
		res = PQexec(g_conn, oidFetchQry->data);

		if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
		{
B
Bruce Momjian 已提交
1258 1259
			fprintf(stderr, "dumpBlobs(): Fetch Cursor failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
			exit_nicely(g_conn);
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
		}

		/* 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 已提交
1271
						"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1272 1273 1274 1275 1276 1277
				exit_nicely(g_conn);
			}

			StartBlob(AH, blobOid);

			/* Now read it in chunks, sending data to archive */
B
Bruce Momjian 已提交
1278 1279
			do
			{
1280
				cnt = lo_read(g_conn, loFd, buf, loBufSize);
B
Bruce Momjian 已提交
1281 1282
				if (cnt < 0)
				{
1283
					fprintf(stderr, "dumpBlobs(): Error reading large object. "
B
Bruce Momjian 已提交
1284
							" Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1285 1286 1287
					exit_nicely(g_conn);
				}

B
Bruce Momjian 已提交
1288
				WriteData(AH, buf, cnt);
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301

			} while (cnt > 0);

			lo_close(g_conn, loFd);

			EndBlob(AH, blobOid);

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

	return 1;
}

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

	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;
1334
	int			i_typedefn;
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346

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

1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
	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");
	}
1363

B
Hi, all  
Bruce Momjian 已提交
1364
	res = PQexec(g_conn, query->data);
1365 1366 1367
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
1368
		fprintf(stderr, "getTypes(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
		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");
1391
	i_typedefn = PQfnumber(res, "typedefn");
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408

	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));
1409
		tinfo[i].typedefn = strdup(PQgetvalue(res, i, i_typedefn));
1410

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

1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
		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;
1434 1435 1436 1437
}

/*
 * getOperators:
1438
 *	  read all operators in the system catalogs and return them in the
1439 1440
 * OprInfo* structure
 *
1441 1442
 *	numOprs is set to the number of operators read in
 *
1443 1444
 *
 */
1445
OprInfo    *
1446 1447
getOperators(int *numOprs)
{
1448
	PGresult   *res;
1449 1450
	int			ntups;
	int			i;
1451
	PQExpBuffer query = createPQExpBuffer();
1452

B
Bruce Momjian 已提交
1453
	OprInfo    *oprinfo;
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468

	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;
1469 1470 1471 1472 1473 1474

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

B
Hi, all  
Bruce Momjian 已提交
1475
	appendPQExpBuffer(query, "SELECT pg_operator.oid, oprname, oprkind, oprcode, "
1476
			   "oprleft, oprright, oprcom, oprnegate, oprrest, oprjoin, "
B
Bruce Momjian 已提交
1477 1478 1479
					  "oprcanhash, oprlsortop, oprrsortop, "
	"(select usename from pg_user where oprowner = usesysid) as usename "
					  "from pg_operator");
1480

B
Hi, all  
Bruce Momjian 已提交
1481
	res = PQexec(g_conn, query->data);
1482 1483 1484
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
1485
		fprintf(stderr, "getOperators(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
		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));
1525 1526 1527

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

1530 1531 1532 1533 1534
	}

	PQclear(res);

	return oprinfo;
1535 1536
}

1537
void
1538
clearTypeInfo(TypeInfo *tp, int numTypes)
1539
{
1540
	int			i;
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573

	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);
1574 1575 1576
}

void
1577
clearFuncInfo(FuncInfo *fun, int numFuncs)
1578
{
1579 1580
	int			i,
				a;
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591

	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);
1592
		for (a = 0; a < FUNC_MAX_ARGS; ++a)
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
			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);
1603 1604
}

1605
static void
1606
clearTableInfo(TableInfo *tblinfo, int numTables)
1607
{
1608 1609
	int			i,
				j;
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629

	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 已提交
1630 1631
			if (tblinfo[i].attoids[j])
				free(tblinfo[i].attoids[j]);
1632 1633 1634 1635 1636
			if (tblinfo[i].attnames[j])
				free(tblinfo[i].attnames[j]);
			if (tblinfo[i].typnames[j])
				free(tblinfo[i].typnames[j]);
		}
B
Bruce Momjian 已提交
1637

B
Bruce Momjian 已提交
1638 1639 1640
		if (tblinfo[i].triggers)
		{
			for (j = 0; j < tblinfo[i].ntrig; j++)
B
Bruce Momjian 已提交
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
			{
				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);
		}

1654 1655
		if (tblinfo[i].atttypmod)
			free((int *) tblinfo[i].atttypmod);
1656 1657
		if (tblinfo[i].inhAttrs)
			free((int *) tblinfo[i].inhAttrs);
1658 1659 1660 1661
		if (tblinfo[i].inhAttrDef)
			free((int *) tblinfo[i].inhAttrDef);
		if (tblinfo[i].inhNotNull)
			free((int *) tblinfo[i].inhNotNull);
1662 1663
		if (tblinfo[i].attnames)
			free(tblinfo[i].attnames);
1664 1665
		if (tblinfo[i].atttypedefns)
			free(tblinfo[i].atttypedefns);
1666 1667 1668 1669
		if (tblinfo[i].typnames)
			free(tblinfo[i].typnames);
		if (tblinfo[i].notnull)
			free(tblinfo[i].notnull);
1670 1671
		if (tblinfo[i].primary_key_name)
			free(tblinfo[i].primary_key_name);
1672 1673
	}
	free(tblinfo);
1674 1675
}

1676
void
1677
clearInhInfo(InhInfo *inh, int numInherits)
1678
{
1679
	int			i;
1680 1681 1682 1683 1684

	if (!inh)
		return;
	for (i = 0; i < numInherits; ++i)
	{
1685 1686
		if (inh[i].inhrelid)
			free(inh[i].inhrelid);
1687 1688 1689 1690
		if (inh[i].inhparent)
			free(inh[i].inhparent);
	}
	free(inh);
1691 1692 1693
}

void
1694
clearOprInfo(OprInfo *opr, int numOprs)
1695
{
1696
	int			i;
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731

	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);
1732 1733 1734
}

void
1735
clearIndInfo(IndInfo *ind, int numIndices)
1736
{
1737 1738
	int			i,
				a;
1739 1740 1741 1742 1743

	if (!ind)
		return;
	for (i = 0; i < numIndices; ++i)
	{
B
Bruce,  
Bruce Momjian 已提交
1744 1745
		if (ind[i].indoid)
			free(ind[i].indoid);
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
		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);
1756 1757
		if (ind[i].indisprimary)
			free(ind[i].indisprimary);
1758 1759 1760 1761 1762 1763 1764 1765 1766
		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);
1767 1768 1769
}

void
B
Bruce Momjian 已提交
1770
clearAggInfo(AggInfo *agginfo, int numArgs)
1771
{
1772
	int			i;
1773 1774 1775 1776 1777 1778 1779 1780 1781

	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);
1782 1783
		if (agginfo[i].aggtransfn)
			free(agginfo[i].aggtransfn);
1784 1785
		if (agginfo[i].aggfinalfn)
			free(agginfo[i].aggfinalfn);
1786 1787
		if (agginfo[i].aggtranstype)
			free(agginfo[i].aggtranstype);
1788 1789
		if (agginfo[i].aggbasetype)
			free(agginfo[i].aggbasetype);
1790 1791
		if (agginfo[i].agginitval)
			free(agginfo[i].agginitval);
1792 1793 1794 1795
		if (agginfo[i].usename)
			free(agginfo[i].usename);
	}
	free(agginfo);
1796
}
1797 1798 1799

/*
 * getAggregates:
1800
 *	  read all the user-defined aggregates in the system catalogs and
1801 1802
 * return them in the AggInfo* structure
 *
1803 1804
 * numAggs is set to the number of aggregates read in
 *
1805 1806
 *
 */
1807
AggInfo    *
1808 1809
getAggregates(int *numAggs)
{
B
Bruce Momjian 已提交
1810
	PGresult   *res;
1811 1812
	int			ntups;
	int			i;
1813
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
1814
	AggInfo    *agginfo;
1815 1816 1817

	int			i_oid;
	int			i_aggname;
1818
	int			i_aggtransfn;
1819
	int			i_aggfinalfn;
1820
	int			i_aggtranstype;
1821
	int			i_aggbasetype;
1822
	int			i_agginitval;
1823
	int			i_usename;
1824
	int			i_convertok;
1825 1826 1827

	/* find all user-defined aggregates */

1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
	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");
	}
1844

B
Hi, all  
Bruce Momjian 已提交
1845
	res = PQexec(g_conn, query->data);
1846 1847 1848
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
1849
		fprintf(stderr, "getAggregates(): SELECT failed.  Explanation from backend: '%s'.\n",
B
Bruce Momjian 已提交
1850
				PQerrorMessage(g_conn));
1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
		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");
1861
	i_aggtransfn = PQfnumber(res, "aggtransfn");
1862
	i_aggfinalfn = PQfnumber(res, "aggfinalfn");
1863
	i_aggtranstype = PQfnumber(res, "aggtranstype");
1864
	i_aggbasetype = PQfnumber(res, "aggbasetype");
1865
	i_agginitval = PQfnumber(res, "agginitval");
1866
	i_usename = PQfnumber(res, "usename");
1867
	i_convertok = PQfnumber(res, "convertok");
1868 1869 1870 1871 1872

	for (i = 0; i < ntups; i++)
	{
		agginfo[i].oid = strdup(PQgetvalue(res, i, i_oid));
		agginfo[i].aggname = strdup(PQgetvalue(res, i, i_aggname));
1873
		agginfo[i].aggtransfn = strdup(PQgetvalue(res, i, i_aggtransfn));
1874
		agginfo[i].aggfinalfn = strdup(PQgetvalue(res, i, i_aggfinalfn));
1875
		agginfo[i].aggtranstype = strdup(PQgetvalue(res, i, i_aggtranstype));
1876
		agginfo[i].aggbasetype = strdup(PQgetvalue(res, i, i_aggbasetype));
1877
		agginfo[i].agginitval = strdup(PQgetvalue(res, i, i_agginitval));
1878
		agginfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1879 1880
		if (strlen(agginfo[i].usename) == 0)
			fprintf(stderr, "WARNING: owner of aggregate '%s' appears to be invalid\n",
B
Bruce Momjian 已提交
1881
					agginfo[i].aggname);
1882

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

1885 1886 1887 1888 1889
	}

	PQclear(res);

	return agginfo;
1890 1891 1892 1893
}

/*
 * getFuncs:
1894
 *	  read all the user-defined functions in the system catalogs and
1895 1896
 * return them in the FuncInfo* structure
 *
1897 1898
 * numFuncs is set to the number of functions read in
 *
1899 1900
 *
 */
1901
FuncInfo   *
1902 1903
getFuncs(int *numFuncs)
{
1904
	PGresult   *res;
1905 1906
	int			ntups;
	int			i;
1907 1908
	PQExpBuffer query = createPQExpBuffer();
	FuncInfo   *finfo;
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918

	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;
1919
	int			i_iscachable;
1920
	int			i_isstrict;
1921
	int			i_usename;
1922 1923 1924

	/* find all user-defined funcs */

1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
	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, "
				"proiscachable, 't'::boolean as proisstrict "
				"from pg_proc "
				"where pg_proc.oid > '%u'::oid",
					  g_last_builtin_oid);
	} else {
		appendPQExpBuffer(query,
1937
		   "SELECT pg_proc.oid, proname, prolang, pronargs, prorettype, "
1938
					  "proretset, proargtypes, prosrc, probin, "
1939 1940 1941 1942
				"(select usename from pg_user where proowner = usesysid) as usename, "
				"proiscachable, proisstrict "
				"from pg_proc "
				"where pg_proc.oid > '%u'::oid",
1943
					  g_last_builtin_oid);
1944
	}
1945

B
Hi, all  
Bruce Momjian 已提交
1946
	res = PQexec(g_conn, query->data);
1947 1948 1949
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
1950 1951
		fprintf(stderr, "getFuncs(): SELECT failed.  Explanation from backend: '%s'.\n",
				PQerrorMessage(g_conn));
1952 1953 1954 1955 1956 1957 1958 1959 1960
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numFuncs = ntups;

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

1961 1962
	memset((char *) finfo, 0, ntups * sizeof(FuncInfo));

1963 1964 1965 1966 1967 1968 1969 1970 1971
	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");
1972
	i_iscachable = PQfnumber(res, "proiscachable");
1973
	i_isstrict = PQfnumber(res, "proisstrict");
1974 1975 1976 1977 1978 1979 1980
	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));

1981
		finfo[i].prosrc = strdup(PQgetvalue(res, i, i_prosrc));
1982 1983 1984 1985 1986
		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));
1987
		finfo[i].lang = atoi(PQgetvalue(res, i, i_prolang));
1988
		finfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
B
Bruce Momjian 已提交
1989 1990
		finfo[i].iscachable = (strcmp(PQgetvalue(res, i, i_iscachable), "t") == 0);
		finfo[i].isstrict = (strcmp(PQgetvalue(res, i, i_isstrict), "t") == 0);
1991 1992 1993

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

1996 1997
		if (finfo[i].nargs < 0 || finfo[i].nargs > FUNC_MAX_ARGS)
		{
1998
			fprintf(stderr, "getFuncs(): failed sanity check: %s has %d args\n",
1999
					finfo[i].proname, finfo[i].nargs);
2000
			exit(1);
2001 2002 2003 2004
		}
		parseNumericArray(PQgetvalue(res, i, i_proargtypes),
						  finfo[i].argtypes,
						  finfo[i].nargs);
2005 2006 2007 2008 2009 2010
		finfo[i].dumped = 0;
	}

	PQclear(res);

	return finfo;
2011 2012 2013 2014 2015

}

/*
 * getTables
2016
 *	  read all the user-defined tables (no indices, no catalogs)
2017 2018
 * in the system catalogs return them in the TableInfo* structure
 *
2019 2020
 * numTables is set to the number of tables read in
 *
2021 2022
 *
 */
2023
TableInfo  *
V
Vadim B. Mikheev 已提交
2024
getTables(int *numTables, FuncInfo *finfo, int numFuncs)
2025
{
2026
	PGresult   *res;
2027 2028
	int			ntups;
	int			i;
2029
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
2030
	PQExpBuffer delqry = createPQExpBuffer();
2031
	TableInfo  *tblinfo;
2032

B
Bruce Momjian 已提交
2033
	int			i_reloid;
2034 2035 2036 2037
	int			i_relname;
	int			i_relkind;
	int			i_relacl;
	int			i_usename;
V
Vadim B. Mikheev 已提交
2038 2039
	int			i_relchecks;
	int			i_reltriggers;
2040
	int			i_relhasindex;
2041 2042 2043 2044 2045

	char		relkindview[2];

	relkindview[0] = RELKIND_VIEW;
	relkindview[1] = '\0';
2046 2047 2048 2049 2050 2051

	/*
	 * 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*
	 *
2052
	 * we ignore tables that are not type 'r' (ordinary relation) or 'S'
2053
	 * (sequence) or 'v' (view).
2054 2055
	 */

2056 2057 2058
	if (g_fout->remoteVersion >= 70100)
	{
		appendPQExpBuffer(query,
B
Bruce Momjian 已提交
2059
					  "SELECT pg_class.oid, relname, relkind, relacl, "
2060
					  "(select usename from pg_user where relowner = usesysid) as usename, "
2061
					  "relchecks, reltriggers, relhasindex "
2062 2063
					  "from pg_class "
					  "where relname !~ '^pg_' "
2064 2065
					  "and relkind in ('%c', '%c', '%c') "
					  "order by oid",
B
Bruce Momjian 已提交
2066
					  RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
	} else {
		/* 
		 * In 7.1, view relkind was not set to 'v', so we fake this by checking
		 * if we have a view by looking up pg_class & pg_rewrite.
		 */
		appendPQExpBuffer(query,
					  "SELECT c.oid, relname, relacl, "
					  "CASE WHEN relhasrules and relkind = 'r' "
					  "           And EXISTS(SELECT r.rulename FROM pg_rewrite r WHERE "
					  "               		r.ev_class = c.oid AND r.ev_type = '1'::\"char\") "
					  "THEN 'v'::\"char\" "
					  "ELSE relkind End AS relkind,"
					  "relacl, (select usename from pg_user where relowner = usesysid) as usename, "
					  "relchecks, reltriggers, relhasindex "
					  "from pg_class c "
					  "where relname !~ '^pg_' "
					  "and relkind in ('%c', '%c', '%c') "
					  "order by oid",
					  RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
	}
2087

B
Hi, all  
Bruce Momjian 已提交
2088
	res = PQexec(g_conn, query->data);
2089 2090 2091
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
2092 2093
		fprintf(stderr, "getTables(): SELECT failed.  Explanation from backend: '%s'.\n",
				PQerrorMessage(g_conn));
2094 2095 2096 2097 2098 2099 2100 2101 2102
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numTables = ntups;

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

B
Bruce Momjian 已提交
2103
	i_reloid = PQfnumber(res, "oid");
2104 2105 2106 2107
	i_relname = PQfnumber(res, "relname");
	i_relkind = PQfnumber(res, "relkind");
	i_relacl = PQfnumber(res, "relacl");
	i_usename = PQfnumber(res, "usename");
V
Vadim B. Mikheev 已提交
2108 2109
	i_relchecks = PQfnumber(res, "relchecks");
	i_reltriggers = PQfnumber(res, "reltriggers");
B
Hi, all  
Bruce Momjian 已提交
2110
	i_relhasindex = PQfnumber(res, "relhasindex");
2111 2112 2113

	for (i = 0; i < ntups; i++)
	{
B
Bruce Momjian 已提交
2114
		tblinfo[i].oid = strdup(PQgetvalue(res, i, i_reloid));
2115 2116 2117 2118
		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 已提交
2119 2120
		tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
		tblinfo[i].ntrig = atoi(PQgetvalue(res, i, i_reltriggers));
2121

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

2126 2127 2128 2129 2130 2131
		/* Get view definition */
		if (strcmp(PQgetvalue(res, i, i_relkind), relkindview) == 0)
		{
			PGresult   *res2;

			resetPQExpBuffer(query);
2132 2133
			appendPQExpBuffer(query, "SELECT definition as viewdef, ");
			/* XXX 7.2 - replace with att from pg_views or some other generic source */
2134 2135 2136
			appendPQExpBuffer(query, "(select oid from pg_rewrite where "
										" rulename=('_RET' || viewname)::name) as view_oid"
										" from pg_views where viewname = ");
2137
			formatStringLiteral(query, tblinfo[i].relname, CONV_ALL);
2138 2139
			appendPQExpBuffer(query, ";");

2140 2141 2142 2143
			res2 = PQexec(g_conn, query->data);
			if (!res2 || PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
				fprintf(stderr, "getTables(): SELECT (for VIEW DEFINITION) failed.  "
B
Bruce Momjian 已提交
2144 2145
						"Explanation from backend: %s",
						PQerrorMessage(g_conn));
2146 2147 2148
				exit_nicely(g_conn);
			}

B
Bruce Momjian 已提交
2149
			if (PQntuples(res2) != 1)
2150 2151 2152
			{
				if (PQntuples(res2) < 1)
				{
2153
					fprintf(stderr, "getTables(): SELECT (for VIEW %s) returned no definitions\n",
B
Bruce Momjian 已提交
2154 2155 2156 2157
							tblinfo[i].relname);
				}
				else
				{
2158
					fprintf(stderr, "getTables(): SELECT (for VIEW %s) returned more than 1 definition\n",
B
Bruce Momjian 已提交
2159
							tblinfo[i].relname);
2160 2161 2162 2163
				}
				exit_nicely(g_conn);
			}

2164 2165 2166 2167 2168 2169 2170
			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);
			}

2171
			tblinfo[i].viewdef = strdup(PQgetvalue(res2, 0, 0));
2172
			tblinfo[i].viewoid = strdup(PQgetvalue(res2, 0, 1));
2173

B
Bruce Momjian 已提交
2174
			if (strlen(tblinfo[i].viewdef) == 0)
2175 2176
			{
				fprintf(stderr, "getTables(): SELECT (for VIEW %s) returned empty definition",
B
Bruce Momjian 已提交
2177
						tblinfo[i].relname);
2178 2179 2180 2181 2182 2183
				exit_nicely(g_conn);
			}
		}
		else
			tblinfo[i].viewdef = NULL;

2184 2185 2186
		/* 
		 * Get non-inherited CHECK constraints, if any.
		 *
B
Bruce Momjian 已提交
2187 2188
		 * Exclude inherited CHECKs from CHECK constraints total. If a
		 * constraint matches by name and condition with a constraint
2189 2190
		 * belonging to a parent class (OR conditions match and both
	     * names start with '$', we assume it was inherited.
2191 2192
		 */
		if (tblinfo[i].ncheck > 0)
V
Vadim B. Mikheev 已提交
2193 2194
		{
			PGresult   *res2;
2195 2196
			int			i_rcname,
						i_rcsrc;
V
Vadim B. Mikheev 已提交
2197 2198
			int			ntups2;
			int			i2;
2199

V
Vadim B. Mikheev 已提交
2200
			if (g_verbose)
2201
				fprintf(stderr, "%s finding CHECK constraints for relation: '%s' %s\n",
V
Vadim B. Mikheev 已提交
2202 2203 2204
						g_comment_start,
						tblinfo[i].relname,
						g_comment_end);
2205

B
Hi, all  
Bruce Momjian 已提交
2206 2207
			resetPQExpBuffer(query);
			appendPQExpBuffer(query, "SELECT rcname, rcsrc from pg_relcheck "
2208
							  " where rcrelid = '%s'::oid "
2209
							  "   and not exists "
2210 2211 2212 2213 2214 2215 2216 2217
							  "  (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) "
2218
							  " Order By oid ",
2219
							  tblinfo[i].oid);
B
Hi, all  
Bruce Momjian 已提交
2220
			res2 = PQexec(g_conn, query->data);
V
Vadim B. Mikheev 已提交
2221
			if (!res2 ||
2222
				PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
2223
			{
B
Bruce Momjian 已提交
2224 2225
				fprintf(stderr, "getTables(): SELECT (for CHECK) failed.  "
						"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
V
Vadim B. Mikheev 已提交
2226 2227 2228
				exit_nicely(g_conn);
			}
			ntups2 = PQntuples(res2);
2229
			if (ntups2 > tblinfo[i].ncheck)
V
Vadim B. Mikheev 已提交
2230
			{
2231 2232
				fprintf(stderr, "getTables(): relation '%s': a maximum of %d CHECKs "
									"were expected, but got %d\n",
2233
						tblinfo[i].relname, tblinfo[i].ncheck, ntups2);
V
Vadim B. Mikheev 已提交
2234 2235
				exit_nicely(g_conn);
			}
2236 2237 2238 2239

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

V
Vadim B. Mikheev 已提交
2240 2241
			i_rcname = PQfnumber(res2, "rcname");
			i_rcsrc = PQfnumber(res2, "rcsrc");
2242
			tblinfo[i].check_expr = (char **) malloc(ntups2 * sizeof(char *));
V
Vadim B. Mikheev 已提交
2243 2244
			for (i2 = 0; i2 < ntups2; i2++)
			{
B
Bruce Momjian 已提交
2245 2246
				const char *name = PQgetvalue(res2, i2, i_rcname);
				const char *expr = PQgetvalue(res2, i2, i_rcsrc);
2247

B
Hi, all  
Bruce Momjian 已提交
2248
				resetPQExpBuffer(query);
2249 2250
				if (name[0] != '$')
				{
2251 2252
					appendPQExpBuffer(query, "CONSTRAINT %s ",
									  fmtId(name, force_quotes));
B
Bruce Momjian 已提交
2253
				}
2254
				appendPQExpBuffer(query, "CHECK (%s)", expr);
B
Hi, all  
Bruce Momjian 已提交
2255
				tblinfo[i].check_expr[i2] = strdup(query->data);
V
Vadim B. Mikheev 已提交
2256 2257 2258 2259 2260
			}
			PQclear(res2);
		}
		else
			tblinfo[i].check_expr = NULL;
2261

2262 2263
		/* Get primary key */
		if (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0)
2264
		{
2265
			PGresult   *res2;
B
Bruce Momjian 已提交
2266

B
Hi, all  
Bruce Momjian 已提交
2267
			resetPQExpBuffer(query);
B
Bruce Momjian 已提交
2268
			appendPQExpBuffer(query,
2269
							  "SELECT Oid FROM pg_index i WHERE i.indisprimary AND i.indrelid = %s ",
2270
							  tblinfo[i].oid);
2271
			res2 = PQexec(g_conn, query->data);
B
Bruce Momjian 已提交
2272 2273
			if (!res2 || PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
2274 2275
				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 已提交
2276 2277
				exit_nicely(g_conn);
			}
2278

B
Bruce Momjian 已提交
2279 2280
			if (PQntuples(res2) > 1)
			{
2281 2282
				fprintf(stderr, "getTables(): SELECT (for PRIMARY KEY) produced more than one row on table %s.\n",
						tblinfo[i].relname);
2283
				exit_nicely(g_conn);
2284 2285
			}

B
Bruce Momjian 已提交
2286
			if (PQntuples(res2) == 1)
2287
				tblinfo[i].pkIndexOid = strdup(PQgetvalue(res2, 0, 0));
B
Bruce Momjian 已提交
2288
			else
2289 2290
				tblinfo[i].pkIndexOid = NULL;

2291
		}
2292
		else
2293
			tblinfo[i].pkIndexOid = NULL;
B
Bruce Momjian 已提交
2294

2295
		/* Get primary key name (if primary key exist) */
2296
		if (tblinfo[i].pkIndexOid != NULL)
2297 2298
		{
			PGresult   *res2;
B
Bruce Momjian 已提交
2299
			int			n;
2300 2301

			resetPQExpBuffer(query);
2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
			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,
2321
							  "SELECT c.relname "
2322
							  "FROM pg_index i LEFT OUTER JOIN pg_class c ON c.oid = i.indexrelid "
2323
							  "WHERE i.indrelid = %s"
2324
							  "AND   i.indisprimary ",
2325
							  tblinfo[i].oid);
2326 2327
			}

2328 2329 2330
			res2 = PQexec(g_conn, query->data);
			if (!res2 || PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
2331 2332
				fprintf(stderr, "getTables(): SELECT (for PRIMARY KEY NAME) failed for table %s.  Explanation from backend: %s",
						tblinfo[i].relname, PQerrorMessage(g_conn));
2333 2334 2335 2336 2337 2338 2339
				exit_nicely(g_conn);
			}

			n = PQntuples(res2);
			if (n != 1)
			{
				fprintf(stderr,
2340
						"getTables(): SELECT (for PRIMARY KEY NAME) failed for table %s. "
B
Bruce Momjian 已提交
2341
						"This is impossible but object with OID == %s have %d primary keys.\n",
2342
						tblinfo[i].relname,
2343 2344 2345 2346 2347
						tblinfo[i].oid,
						n);
				exit_nicely(g_conn);
			}

2348 2349 2350
			/* Sanity check on LOJ */
			if (PQgetisnull(res2, 0, 0))
			{
B
Bruce Momjian 已提交
2351
				fprintf(stderr, "getTables(): SELECT (for PRIMARY KEY NAME) on table %s returned NULL value.\n",
2352 2353 2354 2355
						tblinfo[i].relname);
				exit_nicely(g_conn);
			}

2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
			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 已提交
2367 2368 2369 2370
		/* Get Triggers */
		if (tblinfo[i].ntrig > 0)
		{
			PGresult   *res2;
B
Bruce,  
Bruce Momjian 已提交
2371
			int			i_tgoid,
2372
						i_tgname,
2373 2374 2375
						i_tgfoid,
						i_tgtype,
						i_tgnargs,
2376 2377 2378 2379
						i_tgargs,
						i_tgisconstraint,
						i_tgconstrname,
						i_tgdeferrable,
2380 2381
						i_tgconstrrelid,
						i_tgconstrrelname,
2382
						i_tginitdeferred;
V
Vadim B. Mikheev 已提交
2383 2384
			int			ntups2;
			int			i2;
2385

V
Vadim B. Mikheev 已提交
2386
			if (g_verbose)
2387
				fprintf(stderr, "%s finding Triggers for relation: '%s' %s\n",
V
Vadim B. Mikheev 已提交
2388 2389 2390
						g_comment_start,
						tblinfo[i].relname,
						g_comment_end);
2391

B
Hi, all  
Bruce Momjian 已提交
2392
			resetPQExpBuffer(query);
2393 2394 2395 2396 2397 2398
			appendPQExpBuffer(query, 
								"SELECT tgname, tgfoid, tgtype, tgnargs, tgargs, "
								"tgisconstraint, tgconstrname, tgdeferrable, "
								"tgconstrrelid, tginitdeferred, oid, "
								"(select relname from pg_class where oid = tgconstrrelid) "
								"		as tgconstrrelname "
2399 2400 2401
							  "from pg_trigger "
							  "where tgrelid = '%s'::oid ",
							  tblinfo[i].oid);
B
Hi, all  
Bruce Momjian 已提交
2402
			res2 = PQexec(g_conn, query->data);
V
Vadim B. Mikheev 已提交
2403
			if (!res2 ||
2404
				PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
2405
			{
B
Bruce Momjian 已提交
2406
				fprintf(stderr, "getTables(): SELECT (for TRIGGER) failed.  "
B
Bruce Momjian 已提交
2407
						"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
V
Vadim B. Mikheev 已提交
2408 2409 2410 2411 2412
				exit_nicely(g_conn);
			}
			ntups2 = PQntuples(res2);
			if (ntups2 != tblinfo[i].ntrig)
			{
2413
				fprintf(stderr, "getTables(): relation '%s': %d Triggers were expected, but got %d\n",
2414
						tblinfo[i].relname, tblinfo[i].ntrig, ntups2);
V
Vadim B. Mikheev 已提交
2415 2416 2417 2418 2419 2420 2421
				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 已提交
2422
			i_tgoid = PQfnumber(res2, "oid");
2423 2424 2425
			i_tgisconstraint = PQfnumber(res2, "tgisconstraint");
			i_tgconstrname = PQfnumber(res2, "tgconstrname");
			i_tgdeferrable = PQfnumber(res2, "tgdeferrable");
2426 2427
			i_tgconstrrelid = PQfnumber(res2, "tgconstrrelid");
			i_tgconstrrelname = PQfnumber(res2, "tgconstrrelname");
2428 2429
			i_tginitdeferred = PQfnumber(res2, "tginitdeferred");

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

2447 2448
				tgname = PQgetvalue(res2, i2, i_tgname);

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

				if (strcmp(PQgetvalue(res2, i2, i_tgdeferrable), "f") == 0)
2455
					tgdeferrable = 0;
2456
				else
2457
					tgdeferrable = 1;
2458 2459

				if (strcmp(PQgetvalue(res2, i2, i_tginitdeferred), "f") == 0)
2460
					tginitdeferred = 0;
2461
				else
2462
					tginitdeferred = 1;
2463

V
Vadim B. Mikheev 已提交
2464 2465
				for (findx = 0; findx < numFuncs; findx++)
				{
2466
					if (strcmp(finfo[findx].oid, tgfuncoid) == 0 &&
2467
						finfo[findx].nargs == 0 &&
V
Vadim B. Mikheev 已提交
2468 2469 2470
						strcmp(finfo[findx].prorettype, "0") == 0)
						break;
				}
2471

V
Vadim B. Mikheev 已提交
2472 2473
				if (findx == numFuncs)
				{
2474
					PGresult   *r;
2475
					int			numFuncs;
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492

					/*
					 * 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 已提交
2493
						fprintf(stderr, "getTables(): SELECT (funcname) failed for trigger %s.  Explanation from backend: '%s'.\n",
2494
								tgname, PQerrorMessage(g_conn));
2495 2496 2497 2498 2499
						exit_nicely(g_conn);
					}

					/* Sanity: Check we got only one tuple */
					numFuncs = PQntuples(r);
B
Bruce Momjian 已提交
2500 2501 2502
					if (numFuncs != 1)
					{
						fprintf(stderr, "getTables(): SELECT (funcname) for trigger %s returned %d tuples. Expected 1.\n",
2503
								tgname, numFuncs);
2504 2505
						exit_nicely(g_conn);
					}
2506

2507
					tgfunc = strdup(PQgetvalue(r, 0, PQfnumber(r, "proname")));
2508
					PQclear(r);
2509
				}
2510
				else
2511
					tgfunc = strdup(finfo[findx].proname);
B
Bruce Momjian 已提交
2512

2513
				appendPQExpBuffer(delqry, "DROP TRIGGER %s ", fmtId(tgname, force_quotes));
B
Bruce Momjian 已提交
2514
				appendPQExpBuffer(delqry, "ON %s;\n",
B
Bruce Momjian 已提交
2515
								fmtId(tblinfo[i].relname, force_quotes));
2516

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

2557
				if (tgisconstraint)
2558
				{
2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573
					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));
					}
2574
					if (!tgdeferrable)
2575 2576 2577 2578
						appendPQExpBuffer(query, " NOT");
					appendPQExpBuffer(query, " DEFERRABLE INITIALLY ");
					if (tginitdeferred)
						appendPQExpBuffer(query, "DEFERRED");
2579
					else
2580
						appendPQExpBuffer(query, "IMMEDIATE");
2581

2582 2583 2584
				}

				appendPQExpBuffer(query, " FOR EACH ROW");
2585 2586
				appendPQExpBuffer(query, " EXECUTE PROCEDURE %s (",
								  fmtId(tgfunc, force_quotes));
V
Vadim B. Mikheev 已提交
2587 2588
				for (findx = 0; findx < tgnargs; findx++)
				{
2589
					const char *s;
2590 2591

					for (p = tgargs;;)
V
Vadim B. Mikheev 已提交
2592
					{
2593
						p = strchr(p, '\\');
V
Vadim B. Mikheev 已提交
2594 2595
						if (p == NULL)
						{
B
Bruce Momjian 已提交
2596 2597
							fprintf(stderr, "getTables(): relation '%s': bad argument "
									"string (%s) for trigger '%s'\n",
2598 2599
									tblinfo[i].relname,
									PQgetvalue(res2, i2, i_tgargs),
2600
									tgname);
V
Vadim B. Mikheev 已提交
2601 2602 2603 2604 2605 2606 2607 2608
							exit_nicely(g_conn);
						}
						p++;
						if (*p == '\\')
						{
							p++;
							continue;
						}
2609
						if (p[0] == '0' && p[1] == '0' && p[2] == '0')
V
Vadim B. Mikheev 已提交
2610 2611 2612
							break;
					}
					p--;
2613
					appendPQExpBufferChar(query, '\'');
B
Bruce Momjian 已提交
2614
					for (s = tgargs; s < p;)
V
Vadim B. Mikheev 已提交
2615 2616
					{
						if (*s == '\'')
2617 2618
							appendPQExpBufferChar(query, '\\');
						appendPQExpBufferChar(query, *s++);
V
Vadim B. Mikheev 已提交
2619
					}
B
Bruce Momjian 已提交
2620 2621
					appendPQExpBufferChar(query, '\'');
					appendPQExpBuffer(query, (findx < tgnargs - 1) ? ", " : "");
V
Vadim B. Mikheev 已提交
2622 2623
					tgargs = p + 4;
				}
B
Hi, all  
Bruce Momjian 已提交
2624
				appendPQExpBuffer(query, ");\n");
2625

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

				/*** Initialize trcomments and troids ***/
2629

B
Bruce,  
Bruce Momjian 已提交
2630
				resetPQExpBuffer(query);
2631
				appendPQExpBuffer(query, "TRIGGER %s ",
2632
					fmtId(tgname, force_quotes));
B
Bruce,  
Bruce Momjian 已提交
2633
				appendPQExpBuffer(query, "ON %s",
2634
								fmtId(tblinfo[i].relname, force_quotes));
B
Bruce Momjian 已提交
2635 2636
				tblinfo[i].triggers[i2].tgcomment = strdup(query->data);
				tblinfo[i].triggers[i2].oid = strdup(PQgetvalue(res2, i2, i_tgoid));
2637
				tblinfo[i].triggers[i2].tgname = strdup(fmtId(tgname, false));
B
Bruce Momjian 已提交
2638
				tblinfo[i].triggers[i2].tgdel = strdup(delqry->data);
B
Bruce,  
Bruce Momjian 已提交
2639

2640 2641
				if (tgfunc)
					free(tgfunc);
V
Vadim B. Mikheev 已提交
2642 2643 2644 2645 2646
			}
			PQclear(res2);
		}
		else
			tblinfo[i].triggers = NULL;
2647

2648 2649 2650 2651 2652
	}

	PQclear(res);

	return tblinfo;
2653 2654 2655 2656 2657

}

/*
 * getInherits
2658
 *	  read all the inheritance information
2659 2660
 * from the system catalogs return them in the InhInfo* structure
 *
2661 2662
 * numInherits is set to the number of tables read in
 *
2663 2664
 *
 */
2665
InhInfo    *
2666 2667
getInherits(int *numInherits)
{
2668
	PGresult   *res;
2669 2670
	int			ntups;
	int			i;
2671 2672
	PQExpBuffer query = createPQExpBuffer();
	InhInfo    *inhinfo;
2673

2674
	int			i_inhrelid;
2675
	int			i_inhparent;
2676 2677 2678

	/* find all the inheritance information */

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

B
Hi, all  
Bruce Momjian 已提交
2681
	res = PQexec(g_conn, query->data);
2682 2683 2684
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
2685
		fprintf(stderr, "getInherits(): SELECT failed.  Explanation from backend: '%s'.\n",
B
Bruce Momjian 已提交
2686
				PQerrorMessage(g_conn));
2687 2688 2689 2690 2691 2692 2693 2694 2695
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numInherits = ntups;

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

2696
	i_inhrelid = PQfnumber(res, "inhrelid");
2697 2698 2699 2700
	i_inhparent = PQfnumber(res, "inhparent");

	for (i = 0; i < ntups; i++)
	{
2701
		inhinfo[i].inhrelid = strdup(PQgetvalue(res, i, i_inhrelid));
2702 2703 2704 2705 2706
		inhinfo[i].inhparent = strdup(PQgetvalue(res, i, i_inhparent));
	}

	PQclear(res);
	return inhinfo;
2707 2708 2709 2710
}

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

	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)
2749
			fprintf(stderr, "%s finding the attrs and types for table: '%s' %s\n",
2750 2751 2752 2753
					g_comment_start,
					tblinfo[i].relname,
					g_comment_end);

B
Hi, all  
Bruce Momjian 已提交
2754
		resetPQExpBuffer(q);
2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783

		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 已提交
2784
		res = PQexec(g_conn, q->data);
2785 2786 2787
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
B
Bruce Momjian 已提交
2788
			fprintf(stderr, "getTableAttrs(): SELECT failed.  "
B
Bruce Momjian 已提交
2789
			"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
2790 2791 2792 2793 2794
			exit_nicely(g_conn);
		}

		ntups = PQntuples(res);

B
Bruce,  
Bruce Momjian 已提交
2795
		i_attoid = PQfnumber(res, "attoid");
2796 2797
		i_attname = PQfnumber(res, "attname");
		i_typname = PQfnumber(res, "typname");
2798
		i_atttypmod = PQfnumber(res, "atttypmod");
2799
		i_attnotnull = PQfnumber(res, "attnotnull");
V
Vadim B. Mikheev 已提交
2800
		i_atthasdef = PQfnumber(res, "atthasdef");
2801
		i_atttypedefn = PQfnumber(res, "atttypedefn");
2802 2803

		tblinfo[i].numatts = ntups;
B
Bruce,  
Bruce Momjian 已提交
2804
		tblinfo[i].attoids = (char **) malloc(ntups * sizeof(char *));
2805
		tblinfo[i].attnames = (char **) malloc(ntups * sizeof(char *));
2806
		tblinfo[i].atttypedefns = (char **) malloc(ntups * sizeof(char *));
2807
		tblinfo[i].typnames = (char **) malloc(ntups * sizeof(char *));
2808
		tblinfo[i].atttypmod = (int *) malloc(ntups * sizeof(int));
2809
		tblinfo[i].inhAttrs = (int *) malloc(ntups * sizeof(int));
2810 2811
		tblinfo[i].inhAttrDef = (int *) malloc(ntups * sizeof(int));
		tblinfo[i].inhNotNull = (int *) malloc(ntups * sizeof(int));
2812
		tblinfo[i].notnull = (bool *) malloc(ntups * sizeof(bool));
V
Vadim B. Mikheev 已提交
2813
		tblinfo[i].adef_expr = (char **) malloc(ntups * sizeof(char *));
2814 2815 2816 2817
		tblinfo[i].parentRels = NULL;
		tblinfo[i].numParents = 0;
		for (j = 0; j < ntups; j++)
		{
2818 2819 2820 2821 2822 2823 2824 2825 2826

			/* 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 已提交
2827
			tblinfo[i].attoids[j] = strdup(PQgetvalue(res, j, i_attoid));
2828
			tblinfo[i].attnames[j] = strdup(PQgetvalue(res, j, i_attname));
2829
			tblinfo[i].atttypedefns[j] = strdup(PQgetvalue(res, j, i_atttypedefn));
2830
			tblinfo[i].typnames[j] = strdup(PQgetvalue(res, j, i_typname));
2831
			tblinfo[i].atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
2832 2833
			tblinfo[i].inhAttrs[j] = 0; /* this flag is set in
										 * flagInhAttrs() */
2834 2835 2836
			tblinfo[i].inhAttrDef[j] = 0;
			tblinfo[i].inhNotNull[j] = 0;

2837
			tblinfo[i].notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't') ? true : false;
V
Vadim B. Mikheev 已提交
2838 2839 2840
			if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
			{
				PGresult   *res2;
2841
				int			numAttr;
2842

V
Vadim B. Mikheev 已提交
2843
				if (g_verbose)
2844
					fprintf(stderr, "%s finding DEFAULT expression for attr: '%s' %s\n",
V
Vadim B. Mikheev 已提交
2845 2846 2847
							g_comment_start,
							tblinfo[i].attnames[j],
							g_comment_end);
2848

B
Hi, all  
Bruce Momjian 已提交
2849 2850
				resetPQExpBuffer(q);
				appendPQExpBuffer(q, "SELECT adsrc from pg_attrdef "
2851 2852
							 "where adrelid = '%s'::oid and adnum = %d ",
								  tblinfo[i].oid, j + 1);
B
Hi, all  
Bruce Momjian 已提交
2853
				res2 = PQexec(g_conn, q->data);
V
Vadim B. Mikheev 已提交
2854
				if (!res2 ||
2855
					PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
2856
				{
B
Bruce Momjian 已提交
2857 2858
					fprintf(stderr, "getTableAttrs(): SELECT (for DEFAULT) failed.  "
							"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
V
Vadim B. Mikheev 已提交
2859 2860
					exit_nicely(g_conn);
				}
2861 2862 2863

				/* Sanity: Check we got only one tuple */
				numAttr = PQntuples(res2);
B
Bruce Momjian 已提交
2864 2865 2866 2867
				if (numAttr != 1)
				{
					fprintf(stderr, "getTableAttrs(): SELECT (for DEFAULT) for attr %s returned %d tuples. Expected 1.\n",
							tblinfo[i].attnames[j], numAttr);
2868 2869 2870
					exit_nicely(g_conn);
				}

V
Vadim B. Mikheev 已提交
2871 2872 2873 2874 2875
				tblinfo[i].adef_expr[j] = strdup(PQgetvalue(res2, 0, PQfnumber(res2, "adsrc")));
				PQclear(res2);
			}
			else
				tblinfo[i].adef_expr[j] = NULL;
2876 2877 2878
		}
		PQclear(res);
	}
2879 2880 2881 2882 2883
}


/*
 * getIndices
2884
 *	  read all the user-defined indices information
2885 2886
 * from the system catalogs return them in the InhInfo* structure
 *
2887 2888
 * numIndices is set to the number of indices read in
 *
2889 2890
 *
 */
2891
IndInfo    *
2892 2893
getIndices(int *numIndices)
{
2894
	int			i;
2895
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
2896
	PGresult   *res;
2897
	int			ntups;
B
Bruce Momjian 已提交
2898
	IndInfo    *indinfo;
2899 2900 2901 2902 2903 2904 2905 2906

	int			i_indexrelname;
	int			i_indrelname;
	int			i_indamname;
	int			i_indproc;
	int			i_indkey;
	int			i_indclass;
	int			i_indisunique;
2907
	int			i_indoid;
2908 2909
	int			i_oid;
	int			i_indisprimary;
2910 2911 2912 2913 2914

	/*
	 * find all the user-defined indices. We do not handle partial
	 * indices.
	 *
2915
	 * Notice we skip indices on system classes
2916 2917
	 *
	 * this is a 4-way join !!
2918 2919
	 *
	 * XXXX: Use LOJ
2920 2921
	 */

B
Hi, all  
Bruce Momjian 已提交
2922
	appendPQExpBuffer(query,
2923
					  "SELECT i.oid, t1.oid as indoid, t1.relname as indexrelname, t2.relname as indrelname, "
2924
					  "i.indproc, i.indkey, i.indclass, "
B
Bruce Momjian 已提交
2925
				  "a.amname as indamname, i.indisunique, i.indisprimary "
2926 2927 2928
					"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 "
2929
					  "and t2.relname !~ '^pg_' ",
2930
					  g_last_builtin_oid);
2931

2932 2933 2934
	if (g_fout->remoteVersion < 70100)
		appendPQExpBuffer(query, " and t2.relkind != 'l'");

B
Hi, all  
Bruce Momjian 已提交
2935
	res = PQexec(g_conn, query->data);
2936 2937 2938
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
2939
		fprintf(stderr, "getIndices(): SELECT failed.  "
B
Bruce Momjian 已提交
2940
			"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
2941 2942 2943 2944 2945 2946 2947 2948 2949
		exit_nicely(g_conn);
	}

	ntups = PQntuples(res);

	*numIndices = ntups;

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

2950 2951
	memset((char *) indinfo, 0, ntups * sizeof(IndInfo));

2952
	i_oid = PQfnumber(res, "oid");
B
Bruce,  
Bruce Momjian 已提交
2953
	i_indoid = PQfnumber(res, "indoid");
2954 2955 2956 2957 2958 2959 2960
	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");
2961
	i_indisprimary = PQfnumber(res, "indisprimary");
2962 2963 2964

	for (i = 0; i < ntups; i++)
	{
2965
		indinfo[i].oid = strdup(PQgetvalue(res, i, i_oid));
B
Bruce,  
Bruce Momjian 已提交
2966
		indinfo[i].indoid = strdup(PQgetvalue(res, i, i_indoid));
2967 2968 2969 2970
		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));
2971 2972 2973 2974 2975 2976
		parseNumericArray(PQgetvalue(res, i, i_indkey),
						  indinfo[i].indkey,
						  INDEX_MAX_KEYS);
		parseNumericArray(PQgetvalue(res, i, i_indclass),
						  indinfo[i].indclass,
						  INDEX_MAX_KEYS);
2977
		indinfo[i].indisunique = strdup(PQgetvalue(res, i, i_indisunique));
2978
		indinfo[i].indisprimary = strdup(PQgetvalue(res, i, i_indisprimary));
2979 2980 2981
	}
	PQclear(res);
	return indinfo;
2982 2983
}

B
Bruce,  
Bruce Momjian 已提交
2984
/*------------------------------------------------------------------
2985
 * dumpComments --
B
Bruce,  
Bruce Momjian 已提交
2986
 *
2987
 * This routine is used to dump any comments associated with the
B
Bruce,  
Bruce Momjian 已提交
2988 2989 2990 2991
 * 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
2992
 * addition, the routine takes the stdio FILE handle to which the
B
Bruce,  
Bruce Momjian 已提交
2993 2994 2995 2996
 * output should be written.
 *------------------------------------------------------------------
*/

T
Tom Lane 已提交
2997
static void
B
Bruce Momjian 已提交
2998
dumpComment(Archive *fout, const char *target, const char *oid)
2999
{
B
Bruce,  
Bruce Momjian 已提交
3000

3001
	PGresult   *res;
B
Bruce,  
Bruce Momjian 已提交
3002
	PQExpBuffer query;
3003
	int			i_description;
B
Bruce,  
Bruce Momjian 已提交
3004

3005 3006 3007 3008
	/* Comments are SCHEMA not data */
	if (dataOnly)
		return;

B
Bruce,  
Bruce Momjian 已提交
3009 3010 3011 3012 3013 3014 3015 3016 3017
	/*** 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);
3018 3019
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce,  
Bruce Momjian 已提交
3020 3021 3022 3023 3024 3025 3026
		fprintf(stderr, "DumpComment: SELECT failed: '%s'.\n",
				PQerrorMessage(g_conn));
		exit_nicely(g_conn);
	}

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

3027 3028
	if (PQntuples(res) != 0)
	{
B
Bruce,  
Bruce Momjian 已提交
3029
		i_description = PQfnumber(res, "description");
B
Bruce Momjian 已提交
3030
		resetPQExpBuffer(query);
3031
		appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
3032
		formatStringLiteral(query, PQgetvalue(res, 0, i_description), PASS_LFTAB);
3033
		appendPQExpBuffer(query, ";\n");
B
Bruce Momjian 已提交
3034

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

B
Bruce,  
Bruce Momjian 已提交
3038 3039 3040 3041 3042
	}

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

	PQclear(res);
3043

B
Bruce,  
Bruce Momjian 已提交
3044 3045 3046
}

/*------------------------------------------------------------------
3047
 * dumpDBComment --
B
Bruce,  
Bruce Momjian 已提交
3048
 *
3049 3050
 * 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 已提交
3051 3052 3053 3054 3055
 * to dump the schema of the database, then this is the first
 * statement issued.
 *------------------------------------------------------------------
*/

3056
void
B
Bruce Momjian 已提交
3057
dumpDBComment(Archive *fout)
3058
{
B
Bruce,  
Bruce Momjian 已提交
3059

3060
	PGresult   *res;
B
Bruce,  
Bruce Momjian 已提交
3061
	PQExpBuffer query;
3062
	int			i_oid;
B
Bruce,  
Bruce Momjian 已提交
3063 3064 3065 3066

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

	query = createPQExpBuffer();
3067
	appendPQExpBuffer(query, "SELECT oid FROM pg_database WHERE datname = ");
3068
	formatStringLiteral(query, PQdb(g_conn), CONV_ALL);
B
Bruce,  
Bruce Momjian 已提交
3069 3070 3071 3072

	/*** Execute query ***/

	res = PQexec(g_conn, query->data);
3073 3074
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce,  
Bruce Momjian 已提交
3075 3076 3077 3078 3079 3080 3081
		fprintf(stderr, "dumpDBComment: SELECT failed: '%s'.\n",
				PQerrorMessage(g_conn));
		exit_nicely(g_conn);
	}

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

3082 3083
	if (PQntuples(res) != 0)
	{
B
Bruce,  
Bruce Momjian 已提交
3084 3085 3086 3087 3088 3089 3090 3091 3092
		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);
3093

B
Bruce,  
Bruce Momjian 已提交
3094 3095
}

3096 3097
/*
 * dumpTypes
3098
 *	  writes out to fout the queries to recreate all the user-defined types
3099 3100 3101
 *
 */
void
B
Bruce Momjian 已提交
3102
dumpTypes(Archive *fout, FuncInfo *finfo, int numFuncs,
3103
		  TypeInfo *tinfo, int numTypes)
3104
{
3105
	int			i;
3106
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3107
	PQExpBuffer delq = createPQExpBuffer();
3108
	int			funcInd;
3109 3110 3111 3112
	const char *((*deps)[]);
	int			depIdx = 0;

	deps = malloc(sizeof(char*) * 10);
3113 3114 3115 3116 3117

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

		/* skip all the builtin types */
3118
		if (atooid(tinfo[i].oid) <= g_last_builtin_oid)
3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135
			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)
3136 3137
		{
			(*deps)[depIdx++] = strdup(finfo[funcInd].oid);
3138
			dumpOneFunc(fout, finfo, funcInd, tinfo, numTypes);
3139
		}
3140 3141 3142

		funcInd = findFuncByName(finfo, numFuncs, tinfo[i].typoutput);
		if (funcInd != -1)
3143 3144
		{
			(*deps)[depIdx++] = strdup(finfo[funcInd].oid);
3145
			dumpOneFunc(fout, finfo, funcInd, tinfo, numTypes);
3146
		}
3147

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

B
Hi, all  
Bruce Momjian 已提交
3150 3151
		resetPQExpBuffer(q);
		appendPQExpBuffer(q,
3152
						  "CREATE TYPE %s "
3153
						  "( internallength = %s, externallength = %s,",
3154 3155
						  fmtId(tinfo[i].typname, force_quotes),
						  tinfo[i].typlen,
3156 3157 3158 3159 3160 3161 3162 3163 3164 3165
						  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));
3166
		formatStringLiteral(q, tinfo[i].typdefault, CONV_ALL);
3167 3168 3169

		if (tinfo[i].isArray)
		{
3170
			char	   *elemType;
3171

3172
			elemType = findTypeByOid(tinfo, numTypes, tinfo[i].typelem, zeroAsOpaque);
3173 3174 3175 3176 3177 3178 3179 3180 3181
			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;
			}

3182
			appendPQExpBuffer(q, ", element = %s, delimiter = ", elemType);
3183
			formatStringLiteral(q, tinfo[i].typdelim, CONV_ALL);
3184 3185

			(*deps)[depIdx++] = strdup(tinfo[i].typelem);
3186 3187
		}
		if (tinfo[i].passedbyvalue)
B
Hi, all  
Bruce Momjian 已提交
3188
			appendPQExpBuffer(q, ",passedbyvalue);\n");
3189
		else
B
Hi, all  
Bruce Momjian 已提交
3190
			appendPQExpBuffer(q, ");\n");
3191

3192 3193 3194
		(*deps)[depIdx++] = NULL; /* End of List */

		ArchiveEntry(fout, tinfo[i].oid, tinfo[i].typname, "TYPE", deps,
B
Bruce Momjian 已提交
3195
				  q->data, delq->data, "", tinfo[i].usename, NULL, NULL);
B
Bruce,  
Bruce Momjian 已提交
3196 3197 3198 3199

		/*** Dump Type Comments ***/

		resetPQExpBuffer(q);
B
Bruce Momjian 已提交
3200 3201
		resetPQExpBuffer(delq);

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

B
Bruce Momjian 已提交
3205
		resetPQExpBuffer(q);
3206
	}
3207 3208
}

3209 3210
/*
 * dumpProcLangs
B
Bruce Momjian 已提交
3211
 *		  writes out to fout the queries to recreate user-defined procedural languages
3212 3213 3214
 *
 */
void
B
Bruce Momjian 已提交
3215
dumpProcLangs(Archive *fout, FuncInfo *finfo, int numFuncs,
B
Bruce Momjian 已提交
3216
			  TypeInfo *tinfo, int numTypes)
3217
{
3218 3219
	PGresult   *res;
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
3220 3221
	PQExpBuffer defqry = createPQExpBuffer();
	PQExpBuffer delqry = createPQExpBuffer();
3222
	int			ntups;
B
Bruce Momjian 已提交
3223
	int			i_oid;
3224 3225 3226 3227
	int			i_lanname;
	int			i_lanpltrusted;
	int			i_lanplcallfoid;
	int			i_lancompiler;
3228
	Oid			lanoid;
3229 3230 3231
	char	   *lanname;
	char	   *lancompiler;
	const char *lanplcallfoid;
3232 3233 3234
	int			i,
				fidx;

B
Bruce Momjian 已提交
3235
	appendPQExpBuffer(query, "SELECT oid, * FROM pg_language "
3236 3237
					  "WHERE lanispl "
					  "ORDER BY oid");
B
Hi, all  
Bruce Momjian 已提交
3238
	res = PQexec(g_conn, query->data);
3239 3240 3241
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
3242
		fprintf(stderr, "dumpProcLangs(): SELECT failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
3243 3244 3245 3246
		exit_nicely(g_conn);
	}
	ntups = PQntuples(res);

B
Bruce Momjian 已提交
3247 3248 3249 3250
	i_lanname = PQfnumber(res, "lanname");
	i_lanpltrusted = PQfnumber(res, "lanpltrusted");
	i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
	i_lancompiler = PQfnumber(res, "lancompiler");
B
Bruce Momjian 已提交
3251
	i_oid = PQfnumber(res, "oid");
3252

B
Bruce Momjian 已提交
3253 3254
	for (i = 0; i < ntups; i++)
	{
3255
		lanoid = atooid(PQgetvalue(res, i, i_oid));
3256 3257 3258
		if (lanoid <= g_last_builtin_oid)
			continue;

3259
		lanplcallfoid = PQgetvalue(res, i, i_lanplcallfoid);
3260 3261


3262 3263 3264 3265 3266 3267 3268
		for (fidx = 0; fidx < numFuncs; fidx++)
		{
			if (!strcmp(finfo[fidx].oid, lanplcallfoid))
				break;
		}
		if (fidx >= numFuncs)
		{
B
Bruce Momjian 已提交
3269
			fprintf(stderr, "dumpProcLangs(): handler procedure for "
B
Bruce Momjian 已提交
3270
			   "language %s not found\n", PQgetvalue(res, i, i_lanname));
3271 3272 3273 3274 3275
			exit_nicely(g_conn);
		}

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

3276 3277
		lanname = PQgetvalue(res, i, i_lanname);
		lancompiler = PQgetvalue(res, i, i_lancompiler);
3278

3279
		appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE ");
3280
		formatStringLiteral(delqry, lanname, CONV_ALL);
3281
		appendPQExpBuffer(delqry, ";\n");
3282

3283 3284 3285
		appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE ",
						  (PQgetvalue(res, i, i_lanpltrusted)[0] == 't') ?
						  "TRUSTED " : "");
3286
		formatStringLiteral(defqry, lanname, CONV_ALL);
3287 3288
		appendPQExpBuffer(defqry, " HANDLER %s LANCOMPILER ",
						  fmtId(finfo[fidx].proname, force_quotes));
3289
		formatStringLiteral(defqry, lancompiler, CONV_ALL);
3290
		appendPQExpBuffer(defqry, ";\n");
3291

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

3295 3296
		resetPQExpBuffer(defqry);
		resetPQExpBuffer(delqry);
3297 3298 3299 3300 3301 3302
	}

	PQclear(res);

}

3303 3304
/*
 * dumpFuncs
3305
 *	  writes out to fout the queries to recreate all the user-defined functions
3306 3307 3308
 *
 */
void
B
Bruce Momjian 已提交
3309
dumpFuncs(Archive *fout, FuncInfo *finfo, int numFuncs,
3310
		  TypeInfo *tinfo, int numTypes)
3311
{
3312
	int			i;
3313 3314 3315

	for (i = 0; i < numFuncs; i++)
		dumpOneFunc(fout, finfo, i, tinfo, numTypes);
3316 3317 3318 3319
}

/*
 * dumpOneFunc:
3320 3321
 *	  dump out only one function,  the index of which is given in the third
 *	argument
3322 3323 3324
 *
 */

3325
static void
B
Bruce Momjian 已提交
3326
dumpOneFunc(Archive *fout, FuncInfo *finfo, int i,
3327
			TypeInfo *tinfo, int numTypes)
3328
{
3329
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3330 3331
	PQExpBuffer fn = createPQExpBuffer();
	PQExpBuffer delqry = createPQExpBuffer();
B
Bruce,  
Bruce Momjian 已提交
3332
	PQExpBuffer fnlist = createPQExpBuffer();
B
Bruce Momjian 已提交
3333
	int			j;
3334
	PQExpBuffer asPart = createPQExpBuffer();
3335
	char		func_lang[NAMEDATALEN + 1];
3336 3337 3338 3339
	PGresult   *res;
	int			nlangs;
	int			i_lanname;
	char		query[256];
3340

B
Bruce Momjian 已提交
3341 3342 3343 3344
	char	   *listSep;
	char	   *listSepComma = ",";
	char	   *listSepNone = "";
	char	   *rettypename;
3345

3346 3347 3348 3349 3350
	if (finfo[i].dumped)
		return;
	else
		finfo[i].dumped = 1;

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

3353 3354 3355 3356 3357
	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 已提交
3358
	{
3359 3360
		fprintf(stderr, "dumpOneFunc(): SELECT for procedural language failed.  Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
		exit_nicely(g_conn);
B
Bruce Momjian 已提交
3361
	}
3362 3363 3364
	nlangs = PQntuples(res);

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

3370
	i_lanname = PQfnumber(res, "lanname");
3371

3372
	/*
B
Bruce Momjian 已提交
3373 3374
	 * See backend/commands/define.c for details of how the 'AS' clause is
	 * used.
3375 3376 3377
	 */
	if (strcmp(finfo[i].probin, "-") != 0)
	{
3378
		appendPQExpBuffer(asPart, "AS ");
3379
		formatStringLiteral(asPart, finfo[i].probin, CONV_ALL);
3380
		if (strcmp(finfo[i].prosrc, "-") != 0)
3381 3382
		{
			appendPQExpBuffer(asPart, ", ");
3383
			formatStringLiteral(asPart, finfo[i].prosrc, PASS_LFTAB);
3384
		}
3385 3386 3387 3388
	}
	else
	{
		if (strcmp(finfo[i].prosrc, "-") != 0)
3389 3390
		{
			appendPQExpBuffer(asPart, "AS ");
3391
			formatStringLiteral(asPart, finfo[i].prosrc, PASS_LFTAB);
3392
		}
3393 3394
	}

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

3397
	PQclear(res);
B
Bruce Momjian 已提交
3398

B
Bruce Momjian 已提交
3399 3400
	resetPQExpBuffer(fn);
	appendPQExpBuffer(fn, "%s (", fmtId(finfo[i].proname, force_quotes));
3401 3402
	for (j = 0; j < finfo[i].nargs; j++)
	{
B
Bruce Momjian 已提交
3403
		char	   *typname;
3404

3405
		typname = findTypeByOid(tinfo, numTypes, finfo[i].argtypes[j], zeroAsOpaque);
3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420
		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 已提交
3421 3422 3423
		appendPQExpBuffer(fn, "%s%s",
						  (j > 0) ? "," : "",
						  typname);
B
Bruce,  
Bruce Momjian 已提交
3424
		appendPQExpBuffer(fnlist, "%s%s",
B
Bruce Momjian 已提交
3425 3426
						  (j > 0) ? "," : "",
						  typname);
3427
	}
B
Bruce Momjian 已提交
3428 3429 3430
	appendPQExpBuffer(fn, ")");

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

3433 3434 3435 3436 3437 3438 3439 3440 3441
	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 已提交
3442 3443 3444 3445 3446 3447
		resetPQExpBuffer(q);
		resetPQExpBuffer(fn);
		resetPQExpBuffer(delqry);
		resetPQExpBuffer(fnlist);
		resetPQExpBuffer(asPart);
		return;
3448 3449
	}

B
Bruce Momjian 已提交
3450
	resetPQExpBuffer(q);
B
Bruce Momjian 已提交
3451
	appendPQExpBuffer(q, "CREATE FUNCTION %s ", fn->data);
3452 3453
	appendPQExpBuffer(q, "RETURNS %s%s %s LANGUAGE ",
					  (finfo[i].retset) ? "SETOF " : "",
3454
					  rettypename,
3455
					  asPart->data);
3456
	formatStringLiteral(q, func_lang, CONV_ALL);
3457

B
Bruce Momjian 已提交
3458
	if (finfo[i].iscachable || finfo[i].isstrict)		/* OR in new attrs here */
3459
	{
3460 3461 3462
		appendPQExpBuffer(q, " WITH (");
		listSep = listSepNone;

B
Bruce Momjian 已提交
3463 3464
		if (finfo[i].iscachable)
		{
3465 3466 3467 3468
			appendPQExpBuffer(q, "%s iscachable", listSep);
			listSep = listSepComma;
		}

B
Bruce Momjian 已提交
3469 3470
		if (finfo[i].isstrict)
		{
3471 3472 3473 3474
			appendPQExpBuffer(q, "%s isstrict", listSep);
			listSep = listSepComma;
		}
		appendPQExpBuffer(q, " )");
3475 3476 3477 3478
	}

	appendPQExpBuffer(q, ";\n");

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

B
Bruce,  
Bruce Momjian 已提交
3482 3483 3484 3485 3486 3487 3488 3489
	/*** 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);

3490 3491 3492 3493
}

/*
 * dumpOprs
3494
 *	  writes out to fout the queries to recreate all the user-defined operators
3495 3496
 *
 */
3497
void
B
Bruce Momjian 已提交
3498
dumpOprs(Archive *fout, OprInfo *oprinfo, int numOperators,
3499
		 TypeInfo *tinfo, int numTypes)
3500
{
3501 3502 3503 3504 3505 3506
#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 已提交
3507
	int			i;
3508
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3509
	PQExpBuffer delq = createPQExpBuffer();
3510 3511 3512 3513 3514 3515 3516 3517
	PQExpBuffer leftarg = createPQExpBuffer();
	PQExpBuffer rightarg = createPQExpBuffer();
	PQExpBuffer commutator = createPQExpBuffer();
	PQExpBuffer negator = createPQExpBuffer();
	PQExpBuffer restrictor = createPQExpBuffer();
	PQExpBuffer join = createPQExpBuffer();
	PQExpBuffer sort1 = createPQExpBuffer();
	PQExpBuffer sort2 = createPQExpBuffer();
3518 3519 3520

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

B
Hi, all  
Bruce Momjian 已提交
3523 3524 3525 3526 3527 3528 3529 3530 3531
		resetPQExpBuffer(leftarg);
		resetPQExpBuffer(rightarg);
		resetPQExpBuffer(commutator);
		resetPQExpBuffer(negator);
		resetPQExpBuffer(restrictor);
		resetPQExpBuffer(join);
		resetPQExpBuffer(sort1);
		resetPQExpBuffer(sort2);

3532
		/* skip all the builtin oids */
3533
		if (atooid(oprinfo[i].oid) <= g_last_builtin_oid)
3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549
			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 已提交
3550 3551
			name = findTypeByOid(tinfo, numTypes,
								 oprinfo[i].oprleft, zeroAsOpaque);
3552 3553 3554 3555 3556
			if (name == NULL)
			{
				OPR_NOTICE(oprleft);
				continue;
			}
B
Bruce Momjian 已提交
3557
			appendPQExpBuffer(leftarg, ",\n\tLEFTARG = %s ", name);
3558
		}
3559

3560 3561 3562
		if (strcmp(oprinfo[i].oprkind, "l") == 0 ||
			strcmp(oprinfo[i].oprkind, "b") == 0)
		{
B
Bruce Momjian 已提交
3563 3564
			name = findTypeByOid(tinfo, numTypes,
								 oprinfo[i].oprright, zeroAsOpaque);
3565 3566 3567 3568 3569 3570
			if (name == NULL)
			{
				OPR_NOTICE(oprright);
				continue;
			}
			appendPQExpBuffer(rightarg, ",\n\tRIGHTARG = %s ", name);
3571
		}
3572

B
Hi, all  
Bruce Momjian 已提交
3573
		if (!(strcmp(oprinfo[i].oprcom, "0") == 0))
3574 3575 3576 3577 3578 3579 3580 3581 3582
		{
			name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprcom);
			if (name == NULL)
			{
				OPR_NOTICE(oprcom);
				continue;
			}
			appendPQExpBuffer(commutator, ",\n\tCOMMUTATOR = %s ", name);
		}
3583

B
Hi, all  
Bruce Momjian 已提交
3584
		if (!(strcmp(oprinfo[i].oprnegate, "0") == 0))
3585 3586 3587 3588 3589 3590 3591 3592 3593
		{
			name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprnegate);
			if (name == NULL)
			{
				OPR_NOTICE(oprnegate);
				continue;
			}
			appendPQExpBuffer(negator, ",\n\tNEGATOR = %s ", name);
		}
3594

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

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

B
Hi, all  
Bruce Momjian 已提交
3601
		if (!(strcmp(oprinfo[i].oprlsortop, "0") == 0))
3602
		{
B
Bruce Momjian 已提交
3603
			name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprlsortop);
3604 3605 3606 3607 3608 3609 3610
			if (name == NULL)
			{
				OPR_NOTICE(oprlsortop);
				continue;
			}
			appendPQExpBuffer(sort1, ",\n\tSORT1 = %s ", name);
		}
3611

B
Hi, all  
Bruce Momjian 已提交
3612
		if (!(strcmp(oprinfo[i].oprrsortop, "0") == 0))
3613
		{
B
Bruce Momjian 已提交
3614
			name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprrsortop);
3615 3616 3617 3618 3619 3620 3621
			if (name == NULL)
			{
				OPR_NOTICE(oprrsortop);
				continue;
			}
			appendPQExpBuffer(sort2, ",\n\tSORT2 = %s ", name);
		}
3622

B
Bruce Momjian 已提交
3623 3624
		resetPQExpBuffer(delq);
		appendPQExpBuffer(delq, "DROP OPERATOR %s (%s", oprinfo[i].oprname,
B
Bruce Momjian 已提交
3625
		findTypeByOid(tinfo, numTypes, oprinfo[i].oprleft, zeroAsOpaque));
B
Bruce Momjian 已提交
3626
		appendPQExpBuffer(delq, ", %s);\n",
B
Bruce Momjian 已提交
3627
						  findTypeByOid(tinfo, numTypes, oprinfo[i].oprright, zeroAsOpaque));
3628

B
Hi, all  
Bruce Momjian 已提交
3629 3630
		resetPQExpBuffer(q);
		appendPQExpBuffer(q,
3631 3632 3633 3634 3635 3636 3637 3638 3639
						  "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 已提交
3640
		  (strcmp(oprinfo[i].oprcanhash, "t") == 0) ? ",\n\tHASHES" : "",
3641 3642 3643
						  join->data,
						  sort1->data,
						  sort2->data);
3644

B
Bruce Momjian 已提交
3645
		ArchiveEntry(fout, oprinfo[i].oid, oprinfo[i].oprname, "OPERATOR", NULL,
B
Bruce Momjian 已提交
3646
				q->data, delq->data, "", oprinfo[i].usename, NULL, NULL);
3647
	}
3648 3649 3650 3651
}

/*
 * dumpAggs
3652
 *	  writes out to fout the queries to create all the user-defined aggregates
3653 3654 3655
 *
 */
void
B
Bruce Momjian 已提交
3656
dumpAggs(Archive *fout, AggInfo *agginfo, int numAggs,
3657
		 TypeInfo *tinfo, int numTypes)
3658
{
3659
#define AGG_NOTICE(arg) {\
3660 3661 3662 3663 3664 3665 3666
		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);\
3667 3668
	}

B
Bruce Momjian 已提交
3669
	int			i;
3670
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3671 3672
	PQExpBuffer delq = createPQExpBuffer();
	PQExpBuffer aggSig = createPQExpBuffer();
3673
	PQExpBuffer details = createPQExpBuffer();
3674 3675 3676

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

3679
		resetPQExpBuffer(details);
B
Hi, all  
Bruce Momjian 已提交
3680

3681
		/* skip all the builtin oids */
3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697
		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);
3698
			continue;
3699
		}
3700

3701 3702 3703 3704 3705 3706 3707
		name = findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype, zeroAsAny + useBaseTypeName);
		if (name == NULL)
		{
			AGG_NOTICE(aggbasetype);
			continue;
		}
		appendPQExpBuffer(details, "BASETYPE = %s, ", name);
3708

3709 3710 3711 3712 3713 3714
		name = findTypeByOid(tinfo, numTypes, agginfo[i].aggtranstype, zeroAsOpaque + useBaseTypeName);
		if (name == NULL)
		{
			AGG_NOTICE(aggtranstype);
			continue;
		}
3715 3716
		appendPQExpBuffer(details,
						  "SFUNC = %s, STYPE = %s",
3717
						  agginfo[i].aggtransfn, name);
3718

3719
		if (agginfo[i].agginitval)
3720 3721
		{
			appendPQExpBuffer(details, ", INITCOND = ");
3722
			formatStringLiteral(details, agginfo[i].agginitval, CONV_ALL);
3723
		}
3724

B
Hi, all  
Bruce Momjian 已提交
3725
		if (!(strcmp(agginfo[i].aggfinalfn, "-") == 0))
3726 3727
			appendPQExpBuffer(details, ", FINALFUNC = %s",
							  agginfo[i].aggfinalfn);
3728

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

B
Hi, all  
Bruce Momjian 已提交
3732
		resetPQExpBuffer(q);
3733
		appendPQExpBuffer(q, "CREATE AGGREGATE %s ( %s );\n",
3734
						  agginfo[i].aggname,
3735
						  details->data);
3736

B
Bruce Momjian 已提交
3737
		ArchiveEntry(fout, agginfo[i].oid, aggSig->data, "AGGREGATE", NULL,
B
Bruce Momjian 已提交
3738
				q->data, delq->data, "", agginfo[i].usename, NULL, NULL);
B
Bruce,  
Bruce Momjian 已提交
3739 3740 3741 3742

		/*** Dump Aggregate Comments ***/

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

3747
	}
3748 3749
}

3750 3751 3752 3753 3754
/*
 * These are some support functions to fix the acl problem of pg_dump
 *
 * Matthew C. Aycock 12/02/97
 */
3755 3756 3757

/* Append a keyword to a keyword list, inserting comma if needed.
 * Caller must make aclbuf big enough for all possible keywords.
3758
 */
3759
static void
B
Bruce Momjian 已提交
3760
AddAcl(char *aclbuf, const char *keyword)
3761
{
3762 3763 3764
	if (*aclbuf)
		strcat(aclbuf, ",");
	strcat(aclbuf, keyword);
3765
}
3766

3767
/*
3768
 * This will take a string of 'arwR' and return a malloced,
3769 3770
 * comma delimited string of SELECT,INSERT,UPDATE,DELETE,RULE
 */
V
Vadim B. Mikheev 已提交
3771
static char *
3772
GetPrivileges(const char *s)
3773
{
3774
	char		aclbuf[100];
3775

3776
	aclbuf[0] = '\0';
3777

B
Bruce Momjian 已提交
3778
	if (strchr(s, 'a'))
3779
		AddAcl(aclbuf, "INSERT");
3780

B
Bruce Momjian 已提交
3781
	if (strchr(s, 'w'))
3782
		AddAcl(aclbuf, "UPDATE,DELETE");
B
Bruce Momjian 已提交
3783 3784

	if (strchr(s, 'r'))
3785
		AddAcl(aclbuf, "SELECT");
3786

3787
	if (strchr(s, 'R'))
3788
		AddAcl(aclbuf, "RULE");
3789

3790 3791 3792
	/* Special-case when they're all there */
	if (strcmp(aclbuf, "INSERT,UPDATE,DELETE,SELECT,RULE") == 0)
		return strdup("ALL");
3793

3794
	return strdup(aclbuf);
3795
}
3796

B
Bruce Momjian 已提交
3797
/*
B
Bruce Momjian 已提交
3798
 * The name says it all; a function to append a string is the dest
B
Bruce Momjian 已提交
3799 3800
 * is big enough. If not, it does a realloc.
 */
B
Bruce Momjian 已提交
3801 3802
static void
strcatalloc(char **dest, int *dSize, char *src)
B
Bruce Momjian 已提交
3803
{
B
Bruce Momjian 已提交
3804 3805 3806 3807 3808 3809 3810 3811 3812 3813
	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 已提交
3814 3815


B
Bruce Momjian 已提交
3816 3817
/*
 * dumpACL:
3818 3819
 *	  Write out grant/revoke information
 *	  Called for sequences and tables
B
Bruce Momjian 已提交
3820 3821
 */

3822
static void
B
Bruce Momjian 已提交
3823
dumpACL(Archive *fout, TableInfo tbinfo)
B
Bruce Momjian 已提交
3824
{
B
Bruce Momjian 已提交
3825 3826
	const char *acls = tbinfo.relacl;
	char	   *aclbuf,
B
Bruce Momjian 已提交
3827 3828 3829
			   *tok,
			   *eqpos,
			   *priv;
B
Bruce Momjian 已提交
3830
	char	   *sql;
B
Bruce Momjian 已提交
3831
	char		tmp[1024];
B
Bruce Momjian 已提交
3832
	int			sSize = 4096;
3833 3834 3835 3836

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

B
Bruce Momjian 已提交
3837 3838 3839
	/*
	 * Allocate a larginsh buffer for the output SQL.
	 */
B
Bruce Momjian 已提交
3840
	sql = (char *) malloc(sSize);
B
Bruce Momjian 已提交
3841

B
Bruce Momjian 已提交
3842 3843 3844
	/*
	 * Revoke Default permissions for PUBLIC. Is this actually necessary,
	 * or is it just a waste of time?
3845
	 */
B
Bruce Momjian 已提交
3846
	sprintf(sql, "REVOKE ALL on %s from PUBLIC;\n",
3847
			fmtId(tbinfo.relname, force_quotes));
3848 3849 3850

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

3852 3853
	/* Scan comma-separated ACL items */
	for (tok = strtok(aclbuf, ","); tok != NULL; tok = strtok(NULL, ","))
3854
	{
3855

B
Bruce Momjian 已提交
3856 3857 3858
		/*
		 * Token may start with '{' and/or '"'.  Actually only the start
		 * of the string should have '{', but we don't verify that.
3859 3860 3861 3862 3863 3864 3865 3866
		 */
		if (*tok == '{')
			tok++;
		if (*tok == '"')
			tok++;

		/* User name is string up to = in tok */
		eqpos = strchr(tok, '=');
B
Bruce Momjian 已提交
3867
		if (!eqpos)
B
Bruce Momjian 已提交
3868
		{
3869 3870
			fprintf(stderr, "Could not parse ACL list ('%s') for '%s'...Exiting!\n",
					acls, tbinfo.relname);
B
Bruce Momjian 已提交
3871 3872 3873
			exit_nicely(g_conn);
		}

B
Bruce Momjian 已提交
3874 3875 3876 3877
		/*
		 * Parse the privileges (right-hand side).	Skip if there are
		 * none.
		 */
3878 3879
		priv = GetPrivileges(eqpos + 1);
		if (*priv)
3880
		{
B
Bruce Momjian 已提交
3881
			sprintf(tmp, "GRANT %s on %s to ",
3882
					priv, fmtId(tbinfo.relname, force_quotes));
B
Bruce Momjian 已提交
3883
			strcatalloc(&sql, &sSize, tmp);
B
Bruce Momjian 已提交
3884 3885 3886

			/*
			 * Note: fmtId() can only be called once per printf, so don't
3887 3888 3889 3890 3891
			 * try to merge printing of username into the above printf.
			 */
			if (eqpos == tok)
			{
				/* Empty left-hand side means "PUBLIC" */
B
Bruce Momjian 已提交
3892
				strcatalloc(&sql, &sSize, "PUBLIC;\n");
3893
			}
3894
			else
3895 3896
			{
				*eqpos = '\0';	/* it's ok to clobber aclbuf */
3897
				if (strncmp(tok, "group ", strlen("group ")) == 0)
B
Bruce Momjian 已提交
3898
					sprintf(tmp, "GROUP %s;\n",
3899 3900
							fmtId(tok + strlen("group "), force_quotes));
				else
B
Bruce Momjian 已提交
3901 3902
					sprintf(tmp, "%s;\n", fmtId(tok, force_quotes));
				strcatalloc(&sql, &sSize, tmp);
3903
			}
3904
		}
3905
		free(priv);
B
Bruce Momjian 已提交
3906
	}
3907 3908

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

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

B
Bruce Momjian 已提交
3912 3913
}

3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 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
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));
	}
}
3969

3970 3971
/*
 * dumpTables:
3972
 *	  write out to fout all the user-define tables
3973
 */
3974

3975
void
B
Bruce Momjian 已提交
3976
dumpTables(Archive *fout, TableInfo *tblinfo, int numTables,
3977
		   IndInfo *indinfo, int numIndices,
3978 3979
		   InhInfo *inhinfo, int numInherits,
		   TypeInfo *tinfo, int numTypes, const char *tablename,
B
Bruce Momjian 已提交
3980 3981
		   const bool aclsSkip, const bool oids,
		   const bool schemaOnly, const bool dataOnly)
3982
{
3983 3984
	int			i,
				j,
B
Bruce Momjian 已提交
3985
				k;
3986
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3987
	PQExpBuffer delq = createPQExpBuffer();
3988
	char	   *serialSeq = NULL;		/* implicit sequence name created
B
Bruce Momjian 已提交
3989 3990 3991 3992
										 * by SERIAL datatype */
	const char *serialSeqSuffix = "_id_seq";	/* suffix for implicit
												 * SERIAL sequences */
	char	  **parentRels;		/* list of names of parent relations */
3993
	int			numParents;
B
Bruce Momjian 已提交
3994
	int			actual_atts;	/* number of attrs in this CREATE statment */
3995
	char	   *reltypename;
3996
	char	   *objoid;
3997

V
Vadim B. Mikheev 已提交
3998
	/* First - dump SEQUENCEs */
3999
	if (tablename && strlen(tablename) > 0)
B
Bruce Momjian 已提交
4000 4001 4002 4003 4004
	{
		serialSeq = malloc(strlen(tablename) + strlen(serialSeqSuffix) + 1);
		strcpy(serialSeq, tablename);
		strcat(serialSeq, serialSeqSuffix);
	}
V
Vadim B. Mikheev 已提交
4005 4006 4007 4008
	for (i = 0; i < numTables; i++)
	{
		if (!(tblinfo[i].sequence))
			continue;
B
Bruce Momjian 已提交
4009
		if (!tablename || (!strcmp(tblinfo[i].relname, tablename))
B
Bruce Momjian 已提交
4010
			|| (serialSeq && !strcmp(tblinfo[i].relname, serialSeq)))
V
Vadim B. Mikheev 已提交
4011
		{
B
Bruce Momjian 已提交
4012
			/* becomeUser(fout, tblinfo[i].usename); */
4013
			dumpSequence(fout, tblinfo[i], schemaOnly, dataOnly);
4014
			if (!aclsSkip)
B
Bruce Momjian 已提交
4015
				dumpACL(fout, tblinfo[i]);
V
Vadim B. Mikheev 已提交
4016 4017
		}
	}
B
Bruce Momjian 已提交
4018
	if (tablename)
B
Bruce Momjian 已提交
4019
		free(serialSeq);
4020

4021 4022
	for (i = 0; i < numTables; i++)
	{
4023
		if (tblinfo[i].sequence)/* already dumped */
V
Vadim B. Mikheev 已提交
4024
			continue;
4025

4026
		if (!tablename || (!strcmp(tblinfo[i].relname, tablename)) || (strlen(tablename) == 0))
4027 4028
		{

4029 4030
			resetPQExpBuffer(delq);
			resetPQExpBuffer(q);
4031

4032 4033 4034 4035
			/* Use the view definition if there is one */
			if (tblinfo[i].viewdef != NULL)
			{
				reltypename = "VIEW";
4036
				objoid = tblinfo[i].viewoid;
4037
				appendPQExpBuffer(delq, "DROP VIEW %s;\n", fmtId(tblinfo[i].relname, force_quotes));
4038
				appendPQExpBuffer(q, "CREATE VIEW %s as %s\n", fmtId(tblinfo[i].relname, force_quotes), tblinfo[i].viewdef);
4039

4040 4041
			}
			else
4042
			{
4043
				reltypename = "TABLE";
4044
				objoid = tblinfo[i].oid;
4045 4046
				parentRels = tblinfo[i].parentRels;
				numParents = tblinfo[i].numParents;
B
Bruce Momjian 已提交
4047

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

4050 4051 4052 4053 4054 4055
				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)
4056
					{
4057 4058 4059 4060 4061
						/* Format properly if not first attr */
						if (actual_atts > 0)
							appendPQExpBuffer(q, ",\n\t");

						/* Attr name & type */
4062 4063 4064 4065 4066 4067 4068 4069
						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);
						}
4070 4071

						/* Default value */
4072
						if (tblinfo[i].adef_expr[j] != NULL && tblinfo[i].inhAttrDef[j] == 0)
4073
							appendPQExpBuffer(q, " DEFAULT %s",
B
Bruce Momjian 已提交
4074
											  tblinfo[i].adef_expr[j]);
4075 4076

						/* Not Null constraint */
4077
						if (tblinfo[i].notnull[j] && tblinfo[i].inhNotNull[j] == 0)
4078 4079 4080 4081
							appendPQExpBuffer(q, " NOT NULL");

						actual_atts++;
					}
4082
				}
B
Hi all  
Bruce Momjian 已提交
4083

4084 4085


4086 4087 4088 4089 4090 4091 4092
				/* 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 已提交
4093
									  tblinfo[i].check_expr[k]);
4094
				}
4095

4096 4097
				/* Primary Key */
				if (tblinfo[i].pkIndexOid != NULL)
4098
				{
B
Bruce Momjian 已提交
4099
					PQExpBuffer consDef;
4100 4101 4102 4103

					/* Find the corresponding index */
					for (k = 0; k < numIndices; k++)
					{
B
Bruce Momjian 已提交
4104
						if (strcmp(indinfo[k].oid, tblinfo[i].pkIndexOid) == 0)
4105 4106 4107 4108 4109 4110
							break;
					}

					if (k >= numIndices)
					{
						fprintf(stderr, "dumpTables(): failed sanity check, could not find index (%s) for PK constraint\n",
B
Bruce Momjian 已提交
4111
								tblinfo[i].pkIndexOid);
4112 4113 4114 4115 4116
						exit_nicely(g_conn);
					}

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

B
Bruce Momjian 已提交
4117
					if ((actual_atts + tblinfo[i].ncheck) > 0)
4118
						appendPQExpBuffer(q, ",\n\t");
4119 4120 4121 4122

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

					destroyPQExpBuffer(consDef);
4123
				}
B
Bruce Momjian 已提交
4124

4125

4126
				appendPQExpBuffer(q, "\n)");
4127

4128
				if (numParents > 0)
B
Hi all  
Bruce Momjian 已提交
4129
				{
4130
					appendPQExpBuffer(q, "\nINHERITS (");
4131 4132 4133
					for (k = 0; k < numParents; k++)
					{
						appendPQExpBuffer(q, "%s%s",
B
Bruce Momjian 已提交
4134 4135
										  (k > 0) ? ", " : "",
									 fmtId(parentRels[k], force_quotes));
4136 4137
					}
					appendPQExpBuffer(q, ")");
B
Hi all  
Bruce Momjian 已提交
4138 4139
				}

4140 4141
				appendPQExpBuffer(q, ";\n");
			}
B
Bruce Momjian 已提交
4142

B
Bruce Momjian 已提交
4143 4144
			if (!dataOnly)
			{
4145

4146
				ArchiveEntry(fout, objoid, tblinfo[i].relname,
B
Bruce Momjian 已提交
4147 4148
							 reltypename, NULL, q->data, delq->data, "", tblinfo[i].usename,
							 NULL, NULL);
B
Bruce Momjian 已提交
4149

4150 4151 4152 4153
				if (!aclsSkip)
					dumpACL(fout, tblinfo[i]);

			}
4154

4155
			/* Dump Field Comments */
B
Bruce,  
Bruce Momjian 已提交
4156

4157 4158
			for (j = 0; j < tblinfo[i].numatts; j++)
			{
B
Bruce,  
Bruce Momjian 已提交
4159 4160 4161 4162 4163 4164
				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]);
			}
4165

B
Bruce,  
Bruce Momjian 已提交
4166
			/* Dump Table Comments */
4167

B
Bruce,  
Bruce Momjian 已提交
4168
			resetPQExpBuffer(q);
4169
			appendPQExpBuffer(q, "%s %s", reltypename, fmtId(tblinfo[i].relname, force_quotes));
B
Bruce,  
Bruce Momjian 已提交
4170
			dumpComment(fout, q->data, tblinfo[i].oid);
4171

4172 4173
		}
	}
4174 4175
}

B
Bruce Momjian 已提交
4176 4177
static PQExpBuffer
getPKconstraint(TableInfo *tblInfo, IndInfo *indInfo)
4178
{
B
Bruce Momjian 已提交
4179 4180
	PQExpBuffer pkBuf = createPQExpBuffer();
	int			k;
4181 4182

	appendPQExpBuffer(pkBuf, "Constraint %s Primary Key (",
B
Bruce Momjian 已提交
4183
					  tblInfo->primary_key_name);
4184 4185 4186

	for (k = 0; k < INDEX_MAX_KEYS; k++)
	{
4187 4188
		int			indkey;
		const char *attname;
4189 4190 4191 4192

		indkey = atoi(indInfo->indkey[k]);
		if (indkey == InvalidAttrNumber)
			break;
4193
		attname = getAttrName(indkey, tblInfo);
4194 4195

		appendPQExpBuffer(pkBuf, "%s%s",
B
Bruce Momjian 已提交
4196 4197
						  (k == 0) ? "" : ", ",
						  fmtId(attname, force_quotes));
4198 4199 4200 4201 4202 4203 4204
	}

	appendPQExpBuffer(pkBuf, ")");

	return pkBuf;
}

4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239
/*
 * 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 */
}

4240 4241
/*
 * dumpIndices:
4242
 *	  write out to fout all the user-define indices
4243
 */
4244
void
B
Bruce Momjian 已提交
4245
dumpIndices(Archive *fout, IndInfo *indinfo, int numIndices,
4246
			TableInfo *tblinfo, int numTables, const char *tablename)
4247
{
4248 4249 4250
	int			i,
				k;
	int			tableInd;
4251
	PQExpBuffer attlist = createPQExpBuffer();
B
Bruce Momjian 已提交
4252 4253 4254
	char	   *classname[INDEX_MAX_KEYS];
	char	   *funcname;		/* the name of the function to comput the
								 * index key from */
4255
	int			indclass;
4256
	int			nclass;
4257

4258
	PQExpBuffer q = createPQExpBuffer(),
B
Bruce Momjian 已提交
4259
				delq = createPQExpBuffer(),
B
Hi, all  
Bruce Momjian 已提交
4260 4261
				id1 = createPQExpBuffer(),
				id2 = createPQExpBuffer();
4262
	PGresult   *res;
4263 4264 4265 4266

	for (i = 0; i < numIndices; i++)
	{
		tableInd = findTableByName(tblinfo, numTables,
4267 4268 4269
								   indinfo[i].indrelname);
		if (tableInd < 0)
		{
4270
			fprintf(stderr, "dumpIndices(): failed sanity check, table %s was not found\n",
4271
					indinfo[i].indrelname);
4272
			exit(1);
4273
		}
4274

4275 4276 4277 4278 4279 4280
		/* Handle PK indexes */
		if (strcmp(indinfo[i].indisprimary, "t") == 0)
		{
/*
 *			***PK: Enable this code when ALTER TABLE supports PK constraints. ***
 *
B
Bruce Momjian 已提交
4281
 *			PQExpBuffer consDef = getPKconstraint(&tblinfo[tableInd], &indinfo[i]);
4282 4283 4284
 *
 *			resetPQExpBuffer(attlist);
 *
B
Bruce Momjian 已提交
4285
 *			appendPQExpBuffer(attlist, "Alter Table %s Add %s;",
4286 4287 4288
 *								fmtId(tblinfo[tableInd].relname, force_quotes),
 *								consDef->data);
 *
B
Bruce Momjian 已提交
4289
 *			ArchiveEntry(fout, indinfo[i].oid, tblinfo[tableInd].primary_key_name, "CONSTRAINT", NULL,
4290 4291 4292 4293 4294
 *							attlist->data, "",
 *							"", tblinfo[tableInd].usename, NULL, NULL);
 *
 *			destroyPQExpBuffer(consDef);
 */
B
Bruce Momjian 已提交
4295 4296 4297 4298 4299

			/*
			 * Don't need to do anything else for this system-generated
			 * index
			 */
4300 4301 4302 4303
			continue;
		}


4304 4305 4306 4307
		if (strcmp(indinfo[i].indproc, "0") == 0)
			funcname = NULL;
		else
		{
B
Bruce Momjian 已提交
4308
			int			numFuncs;
4309 4310 4311 4312 4313 4314 4315

			/*
			 * 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 已提交
4316 4317
			resetPQExpBuffer(q);
			appendPQExpBuffer(q,
4318 4319 4320
							  "SELECT proname from pg_proc "
							  "where pg_proc.oid = '%s'::oid",
							  indinfo[i].indproc);
B
Hi, all  
Bruce Momjian 已提交
4321
			res = PQexec(g_conn, q->data);
4322 4323
			if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
			{
B
Bruce Momjian 已提交
4324 4325
				fprintf(stderr, "dumpIndices(): SELECT (funcname) failed.  "
						"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
4326 4327
				exit_nicely(g_conn);
			}
4328 4329 4330

			/* Sanity: Check we got only one tuple */
			numFuncs = PQntuples(res);
B
Bruce Momjian 已提交
4331 4332 4333 4334
			if (numFuncs != 1)
			{
				fprintf(stderr, "dumpIndices(): SELECT (funcname) for index %s returned %d tuples. Expected 1.\n",
						indinfo[i].indrelname, numFuncs);
4335 4336 4337
				exit_nicely(g_conn);
			}

B
Bruce Momjian 已提交
4338
			funcname = strdup(PQgetvalue(res, 0, PQfnumber(res, "proname")));
4339 4340 4341 4342 4343 4344
			PQclear(res);
		}

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

4347 4348 4349
			indclass = atoi(indinfo[i].indclass[nclass]);
			if (indclass == 0)
				break;
B
Hi, all  
Bruce Momjian 已提交
4350 4351
			resetPQExpBuffer(q);
			appendPQExpBuffer(q,
4352 4353 4354
							  "SELECT opcname from pg_opclass "
							  "where pg_opclass.oid = '%u'::oid",
							  indclass);
B
Hi, all  
Bruce Momjian 已提交
4355
			res = PQexec(g_conn, q->data);
4356 4357
			if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
			{
B
Bruce Momjian 已提交
4358
				fprintf(stderr, "dumpIndices(): SELECT (classname) failed.  "
B
Bruce Momjian 已提交
4359
						"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
4360 4361
				exit_nicely(g_conn);
			}
4362 4363 4364

			/* Sanity: Check we got only one tuple */
			numRows = PQntuples(res);
B
Bruce Momjian 已提交
4365 4366 4367 4368
			if (numRows != 1)
			{
				fprintf(stderr, "dumpIndices(): SELECT (classname) for index %s returned %d tuples. Expected 1.\n",
						indinfo[i].indrelname, numRows);
4369 4370 4371
				exit_nicely(g_conn);
			}

B
Bruce Momjian 已提交
4372
			classname[nclass] = strdup(PQgetvalue(res, 0, PQfnumber(res, "opcname")));
4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383
			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 已提交
4384 4385
		resetPQExpBuffer(attlist);
		for (k = 0; k < INDEX_MAX_KEYS; k++)
4386
		{
4387 4388
			int			indkey;
			const char *attname;
4389 4390

			indkey = atoi(indinfo[i].indkey[k]);
B
Bruce Momjian 已提交
4391
			if (indkey == InvalidAttrNumber)
4392
				break;
4393
			attname = getAttrName(indkey, &tblinfo[tableInd]);
4394
			if (funcname)
B
Hi, all  
Bruce Momjian 已提交
4395
				appendPQExpBuffer(attlist, "%s%s",
4396 4397
								  (k == 0) ? "" : ", ",
								  fmtId(attname, force_quotes));
4398 4399 4400 4401 4402
			else
			{
				if (k >= nclass)
				{
					fprintf(stderr, "dumpIndices(): OpClass not found for "
4403
							"attribute '%s' of index '%s'\n",
4404 4405 4406
							attname, indinfo[i].indexrelname);
					exit_nicely(g_conn);
				}
B
Hi, all  
Bruce Momjian 已提交
4407 4408 4409 4410 4411
				resetPQExpBuffer(id1);
				resetPQExpBuffer(id2);
				appendPQExpBuffer(id1, fmtId(attname, force_quotes));
				appendPQExpBuffer(id2, fmtId(classname[k], force_quotes));
				appendPQExpBuffer(attlist, "%s%s %s",
4412 4413
								  (k == 0) ? "" : ", ",
								  id1->data, id2->data);
4414 4415 4416 4417
				free(classname[k]);
			}
		}

B
Bruce Momjian 已提交
4418
		if (!tablename || (strcmp(indinfo[i].indrelname, tablename) == 0) || (strlen(tablename) == 0))
4419
		{
B
Hi, all  
Bruce Momjian 已提交
4420 4421 4422 4423
			resetPQExpBuffer(id1);
			resetPQExpBuffer(id2);
			appendPQExpBuffer(id1, fmtId(indinfo[i].indexrelname, force_quotes));
			appendPQExpBuffer(id2, fmtId(indinfo[i].indrelname, force_quotes));
4424

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

B
Bruce Momjian 已提交
4428 4429
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "CREATE %s INDEX %s on %s using %s (",
B
Bruce Momjian 已提交
4430 4431 4432 4433
			  (strcmp(indinfo[i].indisunique, "t") == 0) ? "UNIQUE" : "",
							  id1->data,
							  id2->data,
							  indinfo[i].indamname);
4434 4435
			if (funcname)
			{
4436
				/* need 2 printf's here cuz fmtId has static return area */
B
Bruce Momjian 已提交
4437
				appendPQExpBuffer(q, " %s", fmtId(funcname, false));
B
Bruce Momjian 已提交
4438 4439
				appendPQExpBuffer(q, " (%s) %s );\n", attlist->data,
								  fmtId(classname[0], force_quotes));
4440 4441 4442 4443
				free(funcname);
				free(classname[0]);
			}
			else
B
Bruce Momjian 已提交
4444
				appendPQExpBuffer(q, " %s );\n", attlist->data);
B
Bruce,  
Bruce Momjian 已提交
4445

4446 4447 4448 4449 4450
			/*
			 * 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 已提交
4451
			ArchiveEntry(fout, tblinfo[tableInd].oid, id1->data, "INDEX", NULL, q->data, delq->data,
B
Bruce Momjian 已提交
4452
						 "", tblinfo[tableInd].usename, NULL, NULL);
B
Bruce Momjian 已提交
4453

4454
			/* Dump Index Comments */
B
Bruce,  
Bruce Momjian 已提交
4455 4456 4457
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "INDEX %s", id1->data);
			dumpComment(fout, q->data, indinfo[i].indoid);
4458

4459 4460
		}
	}
4461 4462

}
4463

4464
/*
B
Bruce Momjian 已提交
4465
 * dumpTuples
4466 4467 4468 4469 4470
 *	  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
4471
 *	  in PostgreSQL.
4472 4473 4474 4475
 *
 * the attrmap passed in tells how to map the attributes copied in to the
 * attributes copied out
 */
4476
#ifdef NOT_USED
4477
void
4478
dumpTuples(PGresult *res, FILE *fout, int *attrmap)
4479
{
4480 4481 4482 4483
	int			j,
				k;
	int			m,
				n;
B
Bruce Momjian 已提交
4484
	char	  **outVals = NULL; /* values to copy out */
4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503

	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++)
			{
4504
				char	   *pval = outVals[k];
4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524

				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);
	}
4525
}
4526

4527
#endif
4528

4529 4530 4531 4532
/*
 * setMaxOid -
 * find the maximum oid and generate a COPY statement to set it
*/
4533

4534
static void
B
Bruce Momjian 已提交
4535
setMaxOid(Archive *fout)
4536
{
B
Bruce Momjian 已提交
4537 4538
	PGresult   *res;
	Oid			max_oid;
B
Bruce Momjian 已提交
4539
	char		sql[1024];
B
Bruce Momjian 已提交
4540
	int			pos;
4541

4542
	res = PQexec(g_conn, "CREATE TEMPORARY TABLE pgdump_oid (dummy int4)");
4543 4544 4545
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
4546
		fprintf(stderr, "Can not create pgdump_oid table.  "
B
Bruce Momjian 已提交
4547
			"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
4548 4549 4550
		exit_nicely(g_conn);
	}
	PQclear(res);
4551
	res = PQexec(g_conn, "INSERT INTO pgdump_oid VALUES (0)");
4552 4553 4554
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
4555
		fprintf(stderr, "Can not insert into pgdump_oid table.  "
B
Bruce Momjian 已提交
4556
			"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
4557 4558 4559 4560 4561 4562 4563 4564 4565
		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);
4566
	res = PQexec(g_conn, "DROP TABLE pgdump_oid;");
4567 4568 4569
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
4570
		fprintf(stderr, "Can not drop pgdump_oid table.  "
B
Bruce Momjian 已提交
4571
			"Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
4572 4573 4574 4575
		exit_nicely(g_conn);
	}
	PQclear(res);
	if (g_verbose)
4576
		fprintf(stderr, "%s maximum system oid is %u %s\n",
4577
				g_comment_start, max_oid, g_comment_end);
4578
	pos = snprintf(sql, 1024, "CREATE TEMPORARY TABLE pgdump_oid (dummy int4);\n");
B
Bruce Momjian 已提交
4579 4580 4581 4582
	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 已提交
4583

4584
	ArchiveEntry(fout, "0", "Max OID", "<Init>", NULL, sql, "", "", "", NULL, NULL);
4585
}
4586 4587 4588

/*
 * findLastBuiltInOid -
4589
 * find the last built in oid
4590 4591
 * we do this by retrieving datlastsysoid from the pg_database entry for this database,
 */
4592

4593
static Oid
4594
findLastBuiltinOid_V71(const char *dbname)
4595
{
B
Bruce Momjian 已提交
4596
	PGresult   *res;
4597
	int			ntups;
4598
	Oid			last_oid;
4599 4600 4601
	PQExpBuffer query = createPQExpBuffer();

	resetPQExpBuffer(query);
4602
	appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
4603
	formatStringLiteral(query, dbname, CONV_ALL);
4604

4605
	res = PQexec(g_conn, query->data);
4606 4607 4608
	if (res == NULL ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
4609
		fprintf(stderr, "pg_dump: error in finding the last system OID. ");
4610
		fprintf(stderr, "Explanation from backend: '%s'.\n", PQerrorMessage(g_conn));
4611 4612 4613
		exit_nicely(g_conn);
	}
	ntups = PQntuples(res);
4614
	if (ntups < 1)
4615
	{
4616 4617
		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");
4618 4619 4620 4621
		exit_nicely(g_conn);
	}
	if (ntups > 1)
	{
4622 4623
		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");
4624 4625
		exit_nicely(g_conn);
	}
4626
	last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
4627 4628
	PQclear(res);
	return last_oid;
4629 4630
}

4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 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
/*
 * 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;
}
4671

4672
static void
4673
dumpSequence(Archive *fout, TableInfo tbinfo, const bool schemaOnly, const bool dataOnly)
4674
{
4675
	PGresult   *res;
B
Bruce Momjian 已提交
4676
	int4		last,
4677 4678 4679 4680
				incby,
				maxv,
				minv,
				cache;
B
Bruce Momjian 已提交
4681
	char		cycled,
B
Bruce Momjian 已提交
4682
				called;
4683 4684
	const char *t;
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
4685
	PQExpBuffer delqry = createPQExpBuffer();
4686

B
Hi, all  
Bruce Momjian 已提交
4687
	appendPQExpBuffer(query,
4688
			"SELECT sequence_name, last_value, increment_by, max_value, "
4689 4690
				  "min_value, cache_value, is_cycled, is_called from %s",
					  fmtId(tbinfo.relname, force_quotes));
4691

B
Hi, all  
Bruce Momjian 已提交
4692
	res = PQexec(g_conn, query->data);
4693 4694
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
B
Bruce Momjian 已提交
4695
		fprintf(stderr, "dumpSequence(%s): SELECT failed.  "
B
Bruce Momjian 已提交
4696
				"Explanation from backend: '%s'.\n", tbinfo.relname, PQerrorMessage(g_conn));
4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725
		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;

4726
	/*
B
Bruce Momjian 已提交
4727 4728
	 * The logic we use for restoring sequences is as follows: -   Add a
	 * basic CREATE SEQUENCE statement (use last_val for start if called
4729 4730 4731 4732
	 * with 'f', else use min_val for start_val).
	 *
	 *	Add a 'SETVAL(seq, last_val, iscalled)' at restore-time iff
	 *  we load data
4733
	 */
4734

4735 4736 4737
	if (!dataOnly)
	{
		PQclear(res);
4738

4739 4740
		resetPQExpBuffer(delqry);
		appendPQExpBuffer(delqry, "DROP SEQUENCE %s;\n", fmtId(tbinfo.relname, force_quotes));
4741

4742 4743
		resetPQExpBuffer(query);
		appendPQExpBuffer(query,
B
Bruce Momjian 已提交
4744
				  "CREATE SEQUENCE %s start %d increment %d maxvalue %d "
4745
						  "minvalue %d  cache %d %s;\n",
B
Bruce Momjian 已提交
4746
						  fmtId(tbinfo.relname, force_quotes),
4747 4748 4749 4750
						  (called == 't') ? minv : last,
						  incby, maxv, minv, cache,
						  (cycled == 't') ? "cycle" : "");

P
Philip Warner 已提交
4751
		ArchiveEntry(fout, tbinfo.oid, tbinfo.relname, "SEQUENCE", NULL,
B
Bruce Momjian 已提交
4752
			  query->data, delqry->data, "", tbinfo.usename, NULL, NULL);
4753
	}
4754

4755 4756 4757 4758 4759 4760
	if (!schemaOnly)
	{
		resetPQExpBuffer(query);
		appendPQExpBuffer(query, "SELECT setval (");
		formatStringLiteral(query, fmtId(tbinfo.relname, force_quotes), CONV_ALL);
		appendPQExpBuffer(query, ", %d, '%c');\n", last, called);
4761

P
Philip Warner 已提交
4762
		ArchiveEntry(fout, tbinfo.oid, tbinfo.relname, "SEQUENCE SET", NULL,
B
Bruce Momjian 已提交
4763
					 query->data, "" /* Del */ , "", "", NULL, NULL);
4764
	}
B
Bruce,  
Bruce Momjian 已提交
4765

4766 4767 4768
	if (!dataOnly)
	{
		/* Dump Sequence Comments */
B
Bruce,  
Bruce Momjian 已提交
4769

4770 4771 4772 4773
		resetPQExpBuffer(query);
		appendPQExpBuffer(query, "SEQUENCE %s", fmtId(tbinfo.relname, force_quotes));
		dumpComment(fout, query->data, tbinfo.oid);
	}
4774
}
V
Vadim B. Mikheev 已提交
4775 4776


4777
static void
B
Bruce Momjian 已提交
4778
dumpTriggers(Archive *fout, const char *tablename,
4779
			 TableInfo *tblinfo, int numTables)
V
Vadim B. Mikheev 已提交
4780
{
4781 4782 4783
	int			i,
				j;

V
Vadim B. Mikheev 已提交
4784 4785 4786
	if (g_verbose)
		fprintf(stderr, "%s dumping out triggers %s\n",
				g_comment_start, g_comment_end);
4787

V
Vadim B. Mikheev 已提交
4788 4789
	for (i = 0; i < numTables; i++)
	{
B
Bruce Momjian 已提交
4790
		if (tablename && (strcmp(tblinfo[i].relname, tablename) != 0) && (strlen(tablename) > 0))
V
Vadim B. Mikheev 已提交
4791
			continue;
4792

V
Vadim B. Mikheev 已提交
4793 4794
		for (j = 0; j < tblinfo[i].ntrig; j++)
		{
B
Bruce Momjian 已提交
4795
			ArchiveEntry(fout, tblinfo[i].triggers[j].oid, tblinfo[i].triggers[j].tgname,
B
Bruce Momjian 已提交
4796 4797
				   "TRIGGER", NULL, tblinfo[i].triggers[j].tgsrc, "", "",
						 tblinfo[i].usename, NULL, NULL);
B
Bruce Momjian 已提交
4798
			dumpComment(fout, tblinfo[i].triggers[j].tgcomment, tblinfo[i].triggers[j].oid);
V
Vadim B. Mikheev 已提交
4799 4800 4801
		}
	}
}
4802 4803


4804
static void
B
Bruce Momjian 已提交
4805
dumpRules(Archive *fout, const char *tablename,
B
Bruce Momjian 已提交
4806
		  TableInfo *tblinfo, int numTables)
4807
{
B
Bruce Momjian 已提交
4808 4809 4810 4811
	PGresult   *res;
	int			nrules;
	int			i,
				t;
4812
	PQExpBuffer query = createPQExpBuffer();
4813

B
Bruce Momjian 已提交
4814
	int			i_definition;
4815
	int			i_oid;
4816
	int			i_owner;
4817
	int			i_rulename;
4818 4819 4820 4821 4822 4823 4824 4825 4826 4827

	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 已提交
4828
		if (tablename && (strcmp(tblinfo[t].relname, tablename) != 0) && (strlen(tablename) > 0))
4829 4830 4831
			continue;

		/*
B
Bruce Momjian 已提交
4832 4833
		 * 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).
4834 4835
		 *
		 * XXXX: Use LOJ here
4836
		 */
B
Hi, all  
Bruce Momjian 已提交
4837
		resetPQExpBuffer(query);
4838
		appendPQExpBuffer(query, "SELECT definition,"
4839
						  "   (select usename from pg_user where pg_class.relowner = usesysid) AS viewowner, "
4840 4841
						  "   pg_rewrite.oid, pg_rewrite.rulename "
						  "FROM pg_rewrite, pg_class, pg_rules "
4842
						  "WHERE pg_class.relname = ");
4843
		formatStringLiteral(query, tblinfo[t].relname, CONV_ALL);
4844
		appendPQExpBuffer(query,
4845 4846
						  "    AND pg_rewrite.ev_class = pg_class.oid "
						  "    AND pg_rules.tablename = pg_class.relname "
B
Bruce Momjian 已提交
4847
					   "    AND pg_rules.rulename = pg_rewrite.rulename "
4848
						  "ORDER BY pg_rewrite.oid");
B
Hi, all  
Bruce Momjian 已提交
4849
		res = PQexec(g_conn, query->data);
4850 4851 4852
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
4853
			fprintf(stderr, "dumpRules(): SELECT failed for rules associated with table \"%s\".\n\tExplanation from backend: '%s'.\n",
B
Bruce Momjian 已提交
4854
					tblinfo[t].relname, PQerrorMessage(g_conn));
4855 4856 4857 4858 4859
			exit_nicely(g_conn);
		}

		nrules = PQntuples(res);
		i_definition = PQfnumber(res, "definition");
4860
		i_owner = PQfnumber(res, "viewowner");
B
Bruce,  
Bruce Momjian 已提交
4861 4862
		i_oid = PQfnumber(res, "oid");
		i_rulename = PQfnumber(res, "rulename");
4863 4864 4865 4866

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

4868 4869
		for (i = 0; i < nrules; i++)
		{
B
Bruce Momjian 已提交
4870
			ArchiveEntry(fout, PQgetvalue(res, i, i_oid), PQgetvalue(res, i, i_rulename),
B
Bruce Momjian 已提交
4871 4872
						 "RULE", NULL, PQgetvalue(res, i, i_definition),
						 "", "", PQgetvalue(res, i, i_owner), NULL, NULL);
4873

B
Bruce,  
Bruce Momjian 已提交
4874 4875 4876 4877 4878
			/* 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));
4879

B
Bruce,  
Bruce Momjian 已提交
4880 4881
		}

4882 4883 4884
		PQclear(res);
	}
}