pg_dump.c 132.0 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * pg_dump.c
4
 *	  pg_dump is a utility for dumping out a postgres database
B
Bruce Momjian 已提交
5
 *	  into a script file.
6 7 8
 *
 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
9
 *
10 11 12 13 14 15
 *	pg_dump will read the system catalogs in a database and
 *	dump out a script that reproduces
 *	the schema of the database in terms of
 *		  user-defined types
 *		  user-defined functions
 *		  tables
16
 *		  indexes
17 18 19
 *		  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.214 2001/07/16 05:06:59 tgl 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
 *	 indexes,tables,inheritance,types,functions and aggregates.
47
 *	 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
 * 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
122
 *		OID of the type functions, but type must be created after
123 124
 *		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
#ifdef ENABLE_NLS
#include <locale.h>
#endif
151 152 153 154 155 156 157
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif

158 159 160 161
#ifndef HAVE_STRDUP
#include "strdup.h"
#endif

162
#include "access/attnum.h"
163
#include "access/htup.h"
164
#include "catalog/pg_class.h"
V
Vadim B. Mikheev 已提交
165
#include "catalog/pg_trigger.h"
166
#include "catalog/pg_type.h"
167

168
#include "libpq-fe.h"
169
#include "libpq/libpq-fs.h"
170 171

#include "pg_dump.h"
B
Bruce Momjian 已提交
172
#include "pg_backup.h"
173
#include "pg_backup_archiver.h"
174

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

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

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

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

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

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

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

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

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


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

240
static void
241
help(const char *progname)
242
{
243 244 245 246
	printf(gettext("%s dumps a database as a text file or to other formats.\n\n"), progname);
	puts(gettext("Usage:"));
	printf(gettext("  %s [options] dbname\n\n"), progname);
	puts(gettext("Options:"));
B
Hi,  
Bruce Momjian 已提交
247 248

#ifdef HAVE_GETOPT_LONG
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 274 275 276 277 278
	puts(gettext(
		"  -a, --data-only          dump only the data, not the schema\n"
		"  -b, --blobs              include BLOB data in dump\n"
		"  -c, --clean              clean (drop) schema prior to create\n"
		"  -C, --create             include commands to create database in dump\n"
		"  -d, --inserts            dump data as INSERT, rather than COPY, commands\n"
		"  -D, --attribute-inserts  dump data as INSERT commands with column names\n"
		"  -f, --file=FILENAME      output file name\n"
		"  -F, --format {c|t|p}     output file format (custom, tar, plain text)\n"
		"  -h, --host=HOSTNAME      database server host name\n"
		"  -i, --ignore-version     proceed even when server version mismatches\n"
		"                           pg_dump version\n"
		"  -n, --no-quotes          suppress most quotes around identifiers\n"
		"  -N, --quotes             enable most quotes around identifiers\n"
		"  -o, --oids               include oids in dump\n"
		"  -O, --no-owner           do not output \\connect commands in plain\n"
		"                           text format\n"
		"  -p, --port=PORT          database server port number\n"
		"  -R, --no-reconnect       disable ALL reconnections to the database in\n"
		"                           plain text format\n"
		"  -s, --schema-only        dump only the schema, no data\n"
		"  -S, --superuser=NAME     specify the superuser user name to use in\n"
		"                           plain text format\n"
		"  -t, --table=TABLE        dump this table only (* for all)\n"
		"  -U, --username=NAME      connect as specified database user\n"
		"  -v, --verbose            verbose mode\n"
		"  -W, --password           force password prompt (should happen automatically)\n"
		"  -x, --no-acl             do not dump privileges (grant/revoke)\n"
		"  -Z, --compress {0-9}     compression level for compressed formats\n"
		));
B
Hi,  
Bruce Momjian 已提交
279
#else
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
	puts(gettext(
		"  -a                       dump only the data, not the schema\n"
		"  -b                       include BLOB data in dump\n"
		"  -c                       clean (drop) schema prior to create\n"
		"  -C                       include commands to create database in dump\n"
		"  -d                       dump data as INSERT, rather than COPY, commands\n"
		"  -D                       dump data as INSERT commands with column names\n"
		"  -f FILENAME              output file name\n"
		"  -F {c|t|p}               output file format (custom, tar, plain text)\n"
		"  -h HOSTNAME              database server host name\n"
		"  -i                       proceed even when server version mismatches\n"
		"                           pg_dump version\n"
		"  -n                       suppress most quotes around identifiers\n"
		"  -N                       enable most quotes around identifiers\n"
		"  -o                       include oids in dump\n"
		"  -O                       do not output \\connect commands in plain\n"
		"                           text format\n"
		"  -p PORT                  database server port number\n"
		"  -R                       disable ALL reconnections to the database in\n"
		"                           plain text format\n"
		"  -s                       dump only the schema, no data\n"
		"  -S NAME                  specify the superuser user name to use in\n"
		"                           plain text format\n"
		"  -t TABLE                 dump this table only (* for all)\n"
		"  -U NAME                  connect as specified database user\n"
		"  -v                       verbose mode\n"
		"  -W                       force password prompt (should happen automatically)\n"
		"  -x                       do not dump privileges (grant/revoke)\n"
		"  -Z {0-9}                 compression level for compressed formats\n"
		));
B
Hi,  
Bruce Momjian 已提交
310
#endif
311 312 313
	puts(gettext("If no database name is not supplied, then the PGDATABASE environment\n"
				 "variable value is used.\n\n"
				 "Report bugs to <pgsql-bugs@postgresql.org>."));
314 315
}

316

317 318
void
exit_nicely(void)
319
{
320 321 322
	PQfinish(g_conn);
	if (g_verbose)
		write_msg(NULL, "*** aborted because of error\n");
323
	exit(1);
324 325 326
}


327 328
#define COPYBUFSIZ		8192

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

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

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

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

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

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

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

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

376
		sprintf(query, "COPY %s TO stdout;", fmtId(classname, force_quotes));
377 378
	}
	res = PQexec(g_conn, query);
379 380
	if (!res ||
		PQresultStatus(res) == PGRES_FATAL_ERROR)
381
	{
382 383 384 385
		write_msg(NULL, "SQL command to dump the contents of table \"%s\" failed\n",
				  classname);
		write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
		write_msg(NULL, "The command was: %s\n", query);
386
		exit_nicely();
387 388 389 390 391
	}
	else
	{
		if (PQresultStatus(res) != PGRES_COPY_OUT)
		{
392 393 394 395 396
			write_msg(NULL, "SQL command to dump the contents of table \"%s\" executed abnormally.\n",
					  classname);
			write_msg(NULL, "The server returned status %d when %d was expected.\n", 
					  PQresultStatus(res), PGRES_COPY_OUT);
			write_msg(NULL, "The command was: %s\n", query);
397
			exit_nicely();
398 399 400 401
		}
		else
		{
			copydone = false;
402

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

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

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

B
Bruce Momjian 已提交
487
	return 1;
488 489
}

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

496 497
	PGresult   *res;
	PQExpBuffer q = createPQExpBuffer();
498 499
	int			tuple;
	int			field;
500

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

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

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

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

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

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

B
Bruce Momjian 已提交
627 628 629 630 631 632 633
	int			i;
	DataDumperPtr dumpFn;
	DumpContext *dumpCtx;
	char	   *oidsPart;
	char		copyBuf[512];
	char	   *copyStmt;

634 635 636 637 638 639
	if (oids == true)
		oidsPart = "WITH OIDS ";
	else
		oidsPart = "";


640
	if (g_verbose)
641 642 643 644 645 646
	{
		if (onlytable == NULL || (strlen(onlytable) == 0))
			write_msg(NULL, "preparing to dump the contents of all %d tables/sequences\n", numTables);
		else
			write_msg(NULL, "preparing to dump the contents of only one table/sequence\n");
	}
647

648 649
	for (i = 0; i < numTables; i++)
	{
650
		const char *classname = tblinfo[i].relname;
651 652

		/* Skip VIEW relations */
653
		if (tblinfo[i].viewdef != NULL)
654
			continue;
655 656

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

659
		if (!onlytable || (strcmp(classname, onlytable) == 0) || (strlen(onlytable) == 0))
660 661
		{
			if (g_verbose)
662
				write_msg(NULL, "preparing to dump the contents of table %s\n", classname);
663

664 665 666
#if 0
			becomeUser(fout, tblinfo[i].usename);
#endif
B
Bruce Momjian 已提交
667

B
Bruce Momjian 已提交
668 669
			dumpCtx = (DumpContext *) malloc(sizeof(DumpContext));
			dumpCtx->tblinfo = (TableInfo *) tblinfo;
B
Bruce Momjian 已提交
670 671
			dumpCtx->tblidx = i;
			dumpCtx->oids = oids;
672

B
Bruce Momjian 已提交
673
			if (!dumpData)		/* Dump/restore using COPY */
674
			{
B
Bruce Momjian 已提交
675 676
				dumpFn = dumpClasses_nodumpData;
				/* dumpClasses_nodumpData(fout, classname, oids); */
B
Bruce Momjian 已提交
677
				sprintf(copyBuf, "COPY %s %sFROM stdin;\n", fmtId(tblinfo[i].relname, force_quotes),
678 679 680
						oidsPart);
				copyStmt = copyBuf;
			}
B
Bruce Momjian 已提交
681 682
			else
/* Restore using INSERT */
683
			{
B
Bruce Momjian 已提交
684 685
				dumpFn = dumpClasses_dumpData;
				/* dumpClasses_dumpData(fout, classname); */
686 687
				copyStmt = NULL;
			}
B
Bruce Momjian 已提交
688

P
Philip Warner 已提交
689
			ArchiveEntry(fout, tblinfo[i].oid, tblinfo[i].relname,
B
Bruce Momjian 已提交
690 691
				"TABLE DATA", NULL, "", "", copyStmt, tblinfo[i].usename,
						 dumpFn, dumpCtx);
692
		}
693
	}
694 695
}

696
int
697
main(int argc, char **argv)
698
{
B
Bruce Momjian 已提交
699 700
	int			c;
	const char *filename = NULL;
B
Bruce Momjian 已提交
701
	const char *format = "p";
B
Bruce Momjian 已提交
702 703 704
	const char *dbname = NULL;
	const char *pghost = NULL;
	const char *pgport = NULL;
705
	const char *username = NULL;
B
Bruce Momjian 已提交
706
	char	   *tablename = NULL;
707
	bool		oids = false;
B
Bruce Momjian 已提交
708 709
	TableInfo  *tblinfo;
	int			numTables;
710
	bool		force_password = false;
B
Bruce Momjian 已提交
711
	int			compressLevel = -1;
712
	bool		ignore_version = false;
713 714
	int			plainText = 0;
	int			outputClean = 0;
715
	int			outputCreate = 0;
716
	int			outputBlobs = 0;
717 718
	int			outputNoOwner = 0;
	int			outputNoReconnect = 0;
B
Bruce Momjian 已提交
719
	char	   *outputSuperuser = NULL;
720

B
Bruce Momjian 已提交
721
	RestoreOptions *ropt;
722

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

B
Hi,  
Bruce Momjian 已提交
754 755
#endif

756 757 758 759 760 761
#ifdef ENABLE_NLS
	setlocale(LC_ALL, "");
	bindtextdomain("pg_dump", LOCALEDIR);
	textdomain("pg_dump");
#endif

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

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

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

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

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

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

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

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

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

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

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

				outputCreate = 1;
				break;

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

915
					}
916
				}
917
				break;
918

919
			case 'u':
920
				force_password = true;
921
				username = simple_prompt("User name: ", 100, true);
922 923 924 925
				break;

			case 'U':
				username = optarg;
926
				break;
927

928 929
			case 'v':			/* verbose */
				g_verbose = true;
930
				break;
931

932 933 934 935
			case 'W':
				force_password = true;
				break;

936 937
			case 'x':			/* skip ACL dump */
				aclsSkip = true;
938
				break;
939

B
Bruce Momjian 已提交
940 941 942
			case 'Z':			/* Compression Level */
				compressLevel = atoi(optarg);
				break;
943

944 945
#ifndef HAVE_GETOPT_LONG
			case '-':
946 947 948 949
				fprintf(stderr,
						gettext("%s was compiled without support for long options.\n"
								"Use --help for help on invocation options.\n"),
						progname);
950 951 952
				exit(1);
				break;
#endif
953
			default:
954
				fprintf(stderr, gettext("Try '%s --help' for more information.\n"), progname);
955
				exit(1);
956 957 958
		}
	}

B
Bruce Momjian 已提交
959 960
	if (optind < (argc - 1))
	{
P
Philip Warner 已提交
961
		fprintf(stderr,
962 963 964
				gettext("%s: too many command line options (first is '%s')\n"
						"Try '%s --help' for more information.\n"),
				progname, argv[optind + 1], progname);
P
Philip Warner 已提交
965 966 967
		exit(1);
	}

968 969 970 971 972 973 974
	/* Get the target database name */
	if (optind < argc)
		dbname = argv[optind];
	else
		dbname = getenv("PGDATABASE");
	if (!dbname)
	{
975
		write_msg(NULL, "no database name specified\n");
976 977 978
		exit(1);
	}

B
Bruce Momjian 已提交
979 980
	if (dataOnly && schemaOnly)
	{
981
		write_msg(NULL, "The options \"schema only\" (-s) and \"data only\" (-a) cannot be used together.\n");
B
Bruce Momjian 已提交
982 983 984
		exit(1);
	}

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

992 993
	if (dumpData == true && oids == true)
	{
994 995
		write_msg(NULL, "INSERT (-d, -D) and OID (-o) options cannot be used together.\n");
		write_msg(NULL, "(The INSERT command cannot set oids.)\n");
996
		exit(1);
997
	}
998

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

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

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

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

		default:
1032
			write_msg(NULL, "invalid output format '%s' specified\n", format);
B
Bruce Momjian 已提交
1033
			exit(1);
B
Bruce Momjian 已提交
1034 1035 1036 1037
	}

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

1042 1043
	/* Let the archiver know how noisy to be */
	g_fout->verbose = g_verbose;
1044

B
Bruce Momjian 已提交
1045 1046
	/*
	 * Open the database using the Archiver, so it knows about it. Errors
1047
	 * mean death. Accept 7.0 & 7.1 database versions.
B
Bruce Momjian 已提交
1048
	 */
1049 1050
	g_fout->minRemoteVersion = 70000;
	g_fout->maxRemoteVersion = 70199;
1051
	g_conn = ConnectDatabase(g_fout, dbname, pghost, pgport, username, force_password, ignore_version);
1052

1053 1054 1055 1056 1057 1058 1059 1060
	/*
	 * Start serializable transaction to dump consistent data
	 */
	{
		PGresult   *res;

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

1064 1065 1066
		PQclear(res);
		res = PQexec(g_conn, "set transaction isolation level serializable");
		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
1067
			exit_horribly(g_fout, NULL, "could not set transaction isolation level to serializable: %s",
B
Bruce Momjian 已提交
1068
						  PQerrorMessage(g_conn));
1069

1070 1071 1072
		PQclear(res);
	}

1073 1074 1075 1076
	if (g_fout->remoteVersion >= 70100)
		g_last_builtin_oid = findLastBuiltinOid_V71(dbname);
	else
		g_last_builtin_oid = findLastBuiltinOid_V70();
1077

1078 1079 1080 1081
	/* Dump the database definition */
	if (!dataOnly)
		dumpDatabase(g_fout);

1082
	if (oids == true)
1083
		setMaxOid(g_fout);
B
Bruce Momjian 已提交
1084 1085

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

1089
	if (!schemaOnly)
B
Bruce Momjian 已提交
1090
		dumpClasses(tblinfo, numTables, g_fout, tablename, oids, force_quotes);
1091 1092

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

1095 1096
	if (!dataOnly)				/* dump indexes and triggers at the end
								 * for performance */
V
Vadim B. Mikheev 已提交
1097 1098
	{
		dumpTriggers(g_fout, tablename, tblinfo, numTables);
1099
		dumpRules(g_fout, tablename, tblinfo, numTables);
V
Vadim B. Mikheev 已提交
1100
	}
1101

1102 1103
	/* Now sort the output nicely */
	SortTocByOID(g_fout);
1104
	MoveToStart(g_fout, "DATABASE");
1105 1106 1107
	MoveToEnd(g_fout, "TABLE DATA");
	MoveToEnd(g_fout, "BLOBS");
	MoveToEnd(g_fout, "INDEX");
1108
	MoveToEnd(g_fout, "CONSTRAINT");
1109 1110
	MoveToEnd(g_fout, "TRIGGER");
	MoveToEnd(g_fout, "RULE");
1111
	MoveToEnd(g_fout, "SEQUENCE SET");
1112

B
Bruce Momjian 已提交
1113
	if (plainText)
B
Bruce Momjian 已提交
1114 1115
	{
		ropt = NewRestoreOptions();
B
Bruce Momjian 已提交
1116
		ropt->filename = (char *) filename;
B
Bruce Momjian 已提交
1117 1118
		ropt->dropSchema = outputClean;
		ropt->aclsSkip = aclsSkip;
1119 1120 1121 1122 1123 1124 1125 1126 1127
		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 已提交
1128 1129

		if (compressLevel == -1)
B
Bruce Momjian 已提交
1130
			ropt->compression = 0;
B
Bruce Momjian 已提交
1131
		else
B
Bruce Momjian 已提交
1132
			ropt->compression = compressLevel;
B
Bruce Momjian 已提交
1133

1134 1135
		ropt->suppressDumpWarnings = true; /* We've already shown them */

B
Bruce Momjian 已提交
1136 1137 1138 1139
		RestoreArchive(g_fout, ropt);
	}

	CloseArchive(g_fout);
1140

1141 1142 1143
	clearTableInfo(tblinfo, numTables);
	PQfinish(g_conn);
	exit(0);
1144 1145
}

1146 1147 1148 1149 1150
/*
 * dumpDatabase:
 *	dump the database definition
 *
 */
B
Bruce Momjian 已提交
1151
static int
1152 1153
dumpDatabase(Archive *AH)
{
B
Bruce Momjian 已提交
1154 1155 1156 1157 1158 1159
	PQExpBuffer dbQry = createPQExpBuffer();
	PQExpBuffer delQry = createPQExpBuffer();
	PQExpBuffer creaQry = createPQExpBuffer();
	PGresult   *res;
	int			ntups;
	int			i_dba;
1160 1161

	if (g_verbose)
1162
		write_msg(NULL, "saving database definition\n");
1163 1164

	/* Get the dba */
1165
	appendPQExpBuffer(dbQry, "select (select usename from pg_user where datdba = usesysid) as dba from pg_database"
B
Bruce Momjian 已提交
1166
					  " where datname = ");
1167
	formatStringLiteral(dbQry, PQdb(g_conn), CONV_ALL);
1168 1169 1170 1171 1172

	res = PQexec(g_conn, dbQry->data);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1173 1174 1175
		write_msg(NULL, "SQL command failed\n");
		write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
		write_msg(NULL, "The command was: %s\n", dbQry->data);
1176
		exit_nicely();
1177 1178 1179 1180
	}

	ntups = PQntuples(res);

1181 1182 1183
	if (ntups <= 0)
	{
		write_msg(NULL, "missing pg_database entry for database \"%s\"\n", PQdb(g_conn));
1184
		exit_nicely();
1185 1186
	}

1187 1188
	if (ntups != 1)
	{
1189 1190
		write_msg(NULL, "query returned more than one (%d) pg_database entry for database \"%s\"\n",
				  ntups, PQdb(g_conn));
1191
		exit_nicely();
1192 1193 1194 1195 1196 1197
	}

	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 已提交
1198 1199 1200 1201
	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 */ );
1202 1203 1204 1205 1206 1207 1208

	PQclear(res);

	return 1;
}


1209 1210 1211 1212 1213 1214
/*
 * dumpBlobs:
 *	dump all blobs
 *
 */

B
Bruce Momjian 已提交
1215
#define loBufSize 16384
1216 1217
#define loFetchSize 1000

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

	if (g_verbose)
1231
		write_msg(NULL, "saving BLOBs\n");
1232 1233

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

	res = PQexec(g_conn, oidQry->data);
	if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
	{
1244
		write_msg(NULL, "dumpBlobs(): cursor declaration failed: %s", PQerrorMessage(g_conn));
1245
		exit_nicely();
1246 1247 1248 1249 1250
	}

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

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

		if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
		{
1259 1260
			write_msg(NULL, "dumpBlobs(): fetch from cursor failed: %s",
					  PQerrorMessage(g_conn));
1261
			exit_nicely();
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
		}

		/* 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)
			{
1272 1273
				write_msg(NULL, "dumpBlobs(): could not open large object: %s",
						  PQerrorMessage(g_conn));
1274
				exit_nicely();
1275 1276 1277 1278 1279
			}

			StartBlob(AH, blobOid);

			/* Now read it in chunks, sending data to archive */
B
Bruce Momjian 已提交
1280 1281
			do
			{
1282
				cnt = lo_read(g_conn, loFd, buf, loBufSize);
B
Bruce Momjian 已提交
1283 1284
				if (cnt < 0)
				{
1285 1286
					write_msg(NULL, "dumpBlobs(): error reading large object: %s",
							  PQerrorMessage(g_conn));
1287
					exit_nicely();
1288 1289
				}

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

			} while (cnt > 0);

			lo_close(g_conn, loFd);

			EndBlob(AH, blobOid);

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

	return 1;
}

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

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

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

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

B
Hi, all  
Bruce Momjian 已提交
1366
	res = PQexec(g_conn, query->data);
1367 1368 1369
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1370
		write_msg(NULL, "query to obtain list of data types failed: %s", PQerrorMessage(g_conn));
1371
		exit_nicely();
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
	}

	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");
1393
	i_typedefn = PQfnumber(res, "typedefn");
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410

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

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

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

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

B
Bruce Momjian 已提交
1456
	OprInfo    *oprinfo;
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471

	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;
1472 1473 1474 1475 1476 1477

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

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

B
Hi, all  
Bruce Momjian 已提交
1484
	res = PQexec(g_conn, query->data);
1485 1486 1487
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1488
		write_msg(NULL, "query to obtain list of operators failed: %s", PQerrorMessage(g_conn));
1489
		exit_nicely();
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 1525 1526 1527
	}

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

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

1533 1534 1535 1536 1537
	}

	PQclear(res);

	return oprinfo;
1538 1539
}

1540
void
1541
clearTypeInfo(TypeInfo *tp, int numTypes)
1542
{
1543
	int			i;
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 1574 1575 1576

	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);
1577 1578 1579
}

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

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

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

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

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

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

1679
void
1680
clearInhInfo(InhInfo *inh, int numInherits)
1681
{
1682
	int			i;
1683 1684 1685 1686 1687

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

void
1697
clearOprInfo(OprInfo *opr, int numOprs)
1698
{
1699
	int			i;
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 1732 1733 1734

	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);
1735 1736 1737
}

void
1738
clearIndInfo(IndInfo *ind, int numIndexes)
1739
{
1740 1741
	int			i,
				a;
1742 1743 1744

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

void
B
Bruce Momjian 已提交
1775
clearAggInfo(AggInfo *agginfo, int numArgs)
1776
{
1777
	int			i;
1778 1779 1780 1781 1782 1783 1784 1785 1786

	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);
1787 1788
		if (agginfo[i].aggtransfn)
			free(agginfo[i].aggtransfn);
1789 1790
		if (agginfo[i].aggfinalfn)
			free(agginfo[i].aggfinalfn);
1791 1792
		if (agginfo[i].aggtranstype)
			free(agginfo[i].aggtranstype);
1793 1794
		if (agginfo[i].aggbasetype)
			free(agginfo[i].aggbasetype);
1795 1796
		if (agginfo[i].agginitval)
			free(agginfo[i].agginitval);
1797 1798 1799 1800
		if (agginfo[i].usename)
			free(agginfo[i].usename);
	}
	free(agginfo);
1801
}
1802 1803 1804

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

	int			i_oid;
	int			i_aggname;
1823
	int			i_aggtransfn;
1824
	int			i_aggfinalfn;
1825
	int			i_aggtranstype;
1826
	int			i_aggbasetype;
1827
	int			i_agginitval;
1828
	int			i_usename;
1829
	int			i_convertok;
1830 1831 1832

	/* find all user-defined aggregates */

1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
	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");
	}
1849

B
Hi, all  
Bruce Momjian 已提交
1850
	res = PQexec(g_conn, query->data);
1851 1852 1853
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1854
		write_msg(NULL, "query to obtain list of aggregate functions failed: %s",
1855
				  PQerrorMessage(g_conn));
1856
		exit_nicely();
1857 1858 1859 1860 1861 1862 1863 1864 1865
	}

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

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

	i_oid = PQfnumber(res, "oid");
	i_aggname = PQfnumber(res, "aggname");
1866
	i_aggtransfn = PQfnumber(res, "aggtransfn");
1867
	i_aggfinalfn = PQfnumber(res, "aggfinalfn");
1868
	i_aggtranstype = PQfnumber(res, "aggtranstype");
1869
	i_aggbasetype = PQfnumber(res, "aggbasetype");
1870
	i_agginitval = PQfnumber(res, "agginitval");
1871
	i_usename = PQfnumber(res, "usename");
1872
	i_convertok = PQfnumber(res, "convertok");
1873 1874 1875 1876 1877

	for (i = 0; i < ntups; i++)
	{
		agginfo[i].oid = strdup(PQgetvalue(res, i, i_oid));
		agginfo[i].aggname = strdup(PQgetvalue(res, i, i_aggname));
1878
		agginfo[i].aggtransfn = strdup(PQgetvalue(res, i, i_aggtransfn));
1879
		agginfo[i].aggfinalfn = strdup(PQgetvalue(res, i, i_aggfinalfn));
1880
		agginfo[i].aggtranstype = strdup(PQgetvalue(res, i, i_aggtranstype));
1881
		agginfo[i].aggbasetype = strdup(PQgetvalue(res, i, i_aggbasetype));
1882
		agginfo[i].agginitval = strdup(PQgetvalue(res, i, i_agginitval));
1883
		agginfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1884
		if (strlen(agginfo[i].usename) == 0)
1885 1886
			write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
					  agginfo[i].aggname);
1887

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

1890 1891 1892 1893 1894
	}

	PQclear(res);

	return agginfo;
1895 1896 1897 1898
}

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

	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;
1924
	int			i_iscachable;
1925
	int			i_isstrict;
1926
	int			i_usename;
1927 1928 1929

	/* find all user-defined funcs */

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

B
Hi, all  
Bruce Momjian 已提交
1951
	res = PQexec(g_conn, query->data);
1952 1953 1954
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
1955 1956
		write_msg(NULL, "query to obtain list of functions failed: %s",
				  PQerrorMessage(g_conn));
1957
		exit_nicely();
1958 1959 1960 1961 1962 1963 1964 1965
	}

	ntups = PQntuples(res);

	*numFuncs = ntups;

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

1966 1967
	memset((char *) finfo, 0, ntups * sizeof(FuncInfo));

1968 1969 1970 1971 1972 1973 1974 1975 1976
	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");
1977
	i_iscachable = PQfnumber(res, "proiscachable");
1978
	i_isstrict = PQfnumber(res, "proisstrict");
1979 1980 1981 1982 1983 1984 1985
	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));

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

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

2001 2002
		if (finfo[i].nargs < 0 || finfo[i].nargs > FUNC_MAX_ARGS)
		{
2003 2004
			write_msg(NULL, "failed sanity check: function %s has more than %d (namely %d) arguments\n",
					  finfo[i].proname, FUNC_MAX_ARGS, finfo[i].nargs);
2005
			exit_nicely();
2006 2007 2008 2009
		}
		parseNumericArray(PQgetvalue(res, i, i_proargtypes),
						  finfo[i].argtypes,
						  finfo[i].nargs);
2010 2011 2012 2013 2014 2015
		finfo[i].dumped = 0;
	}

	PQclear(res);

	return finfo;
2016 2017 2018 2019 2020

}

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

B
Bruce Momjian 已提交
2038
	int			i_reloid;
2039 2040 2041 2042
	int			i_relname;
	int			i_relkind;
	int			i_relacl;
	int			i_usename;
V
Vadim B. Mikheev 已提交
2043 2044
	int			i_relchecks;
	int			i_reltriggers;
2045
	int			i_relhasindex;
2046 2047 2048 2049 2050

	char		relkindview[2];

	relkindview[0] = RELKIND_VIEW;
	relkindview[1] = '\0';
2051 2052

	/*
2053
	 * find all the user-defined tables (no indexes and no catalogs),
2054 2055 2056
	 * ordering by oid is important so that we always process the parent
	 * tables before the child tables when traversing the tblinfo*
	 *
2057
	 * we ignore tables that are not type 'r' (ordinary relation) or 'S'
2058
	 * (sequence) or 'v' (view).
2059 2060
	 */

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

B
Hi, all  
Bruce Momjian 已提交
2094
	res = PQexec(g_conn, query->data);
2095 2096 2097
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
2098 2099
		write_msg(NULL, "query to obtain list of tables failed: %s",
				  PQerrorMessage(g_conn));
2100
		exit_nicely();
2101 2102 2103 2104 2105 2106 2107 2108
	}

	ntups = PQntuples(res);

	*numTables = ntups;

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

B
Bruce Momjian 已提交
2109
	i_reloid = PQfnumber(res, "oid");
2110 2111
	i_relname = PQfnumber(res, "relname");
	i_relacl = PQfnumber(res, "relacl");
2112
	i_relkind = PQfnumber(res, "relkind");
2113
	i_usename = PQfnumber(res, "usename");
V
Vadim B. Mikheev 已提交
2114 2115
	i_relchecks = PQfnumber(res, "relchecks");
	i_reltriggers = PQfnumber(res, "reltriggers");
B
Hi, all  
Bruce Momjian 已提交
2116
	i_relhasindex = PQfnumber(res, "relhasindex");
2117 2118 2119

	for (i = 0; i < ntups; i++)
	{
B
Bruce Momjian 已提交
2120
		tblinfo[i].oid = strdup(PQgetvalue(res, i, i_reloid));
2121 2122 2123 2124
		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 已提交
2125 2126
		tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
		tblinfo[i].ntrig = atoi(PQgetvalue(res, i, i_reltriggers));
2127

2128
		if (strlen(tblinfo[i].usename) == 0)
2129 2130
			write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
					  tblinfo[i].relname);
2131

2132 2133 2134 2135 2136 2137
		/* Get view definition */
		if (strcmp(PQgetvalue(res, i, i_relkind), relkindview) == 0)
		{
			PGresult   *res2;

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

2146 2147 2148
			res2 = PQexec(g_conn, query->data);
			if (!res2 || PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
2149 2150
				write_msg(NULL, "query to obtain definition of view \"%s\" failed: %s",
						  tblinfo[i].relname, PQerrorMessage(g_conn));
2151
				exit_nicely();
2152 2153
			}

B
Bruce Momjian 已提交
2154
			if (PQntuples(res2) != 1)
2155 2156
			{
				if (PQntuples(res2) < 1)
2157 2158
					write_msg(NULL, "query to obtain definition of view \"%s\" returned no data\n",
							  tblinfo[i].relname);
B
Bruce Momjian 已提交
2159
				else
2160
					write_msg(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
B
Bruce Momjian 已提交
2161
							tblinfo[i].relname);
2162
				exit_nicely();
2163 2164
			}

2165 2166
			if (PQgetisnull(res2, 0, 1))
			{
2167 2168
				write_msg(NULL, "query to obtain definition of view \"%s\" returned NULL oid\n",
						  tblinfo[i].relname);
2169
				exit_nicely();
2170 2171
			}

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

B
Bruce Momjian 已提交
2175
			if (strlen(tblinfo[i].viewdef) == 0)
2176
			{
2177 2178
				write_msg(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
						  tblinfo[i].relname);
2179
				exit_nicely();
2180 2181 2182 2183 2184
			}
		}
		else
			tblinfo[i].viewdef = NULL;

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

V
Vadim B. Mikheev 已提交
2201
			if (g_verbose)
2202 2203
				write_msg(NULL, "finding CHECK constraints for table %s\n",
						  tblinfo[i].relname);
2204

B
Hi, all  
Bruce Momjian 已提交
2205 2206
			resetPQExpBuffer(query);
			appendPQExpBuffer(query, "SELECT rcname, rcsrc from pg_relcheck "
2207
							  " where rcrelid = '%s'::oid "
2208
							  "   and not exists "
2209 2210 2211 2212 2213 2214 2215 2216
							  "  (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) "
2217
							  " Order By oid ",
2218
							  tblinfo[i].oid);
B
Hi, all  
Bruce Momjian 已提交
2219
			res2 = PQexec(g_conn, query->data);
V
Vadim B. Mikheev 已提交
2220
			if (!res2 ||
2221
				PQresultStatus(res2) != PGRES_TUPLES_OK)
V
Vadim B. Mikheev 已提交
2222
			{
2223
				write_msg(NULL, "query to obtain check constraints failed: %s", PQerrorMessage(g_conn));
2224
				exit_nicely();
V
Vadim B. Mikheev 已提交
2225 2226
			}
			ntups2 = PQntuples(res2);
2227
			if (ntups2 > tblinfo[i].ncheck)
V
Vadim B. Mikheev 已提交
2228
			{
2229 2230 2231
				write_msg(NULL, "expected %d check constraints on table \"%s\" but found %d\n",
						  tblinfo[i].ncheck, tblinfo[i].relname, ntups2);
				write_msg(NULL, "(The system catalogs might be corrupted.)\n");
2232
				exit_nicely();
V
Vadim B. Mikheev 已提交
2233
			}
2234 2235 2236 2237

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

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

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

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

B
Hi, all  
Bruce Momjian 已提交
2265
			resetPQExpBuffer(query);
B
Bruce Momjian 已提交
2266
			appendPQExpBuffer(query,
2267
							  "SELECT Oid FROM pg_index i WHERE i.indisprimary AND i.indrelid = %s ",
2268
							  tblinfo[i].oid);
2269
			res2 = PQexec(g_conn, query->data);
B
Bruce Momjian 已提交
2270 2271
			if (!res2 || PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
2272 2273
				write_msg(NULL, "query to obtain primary key of table \"%s\" failed: %s",
						  tblinfo[i].relname, PQerrorMessage(g_conn));
2274
				exit_nicely();
B
Bruce Momjian 已提交
2275
			}
2276

B
Bruce Momjian 已提交
2277 2278
			if (PQntuples(res2) > 1)
			{
2279
				write_msg(NULL, "query to obtain primary key of table \"%s\" produced more than one result\n",
2280
						tblinfo[i].relname);
2281
				exit_nicely();
2282 2283
			}

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

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

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

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

2326 2327 2328
			res2 = PQexec(g_conn, query->data);
			if (!res2 || PQresultStatus(res2) != PGRES_TUPLES_OK)
			{
2329 2330
				write_msg(NULL, "query to obtain name of primary key of table \"%s\" failed: %s",
						  tblinfo[i].relname, PQerrorMessage(g_conn));
2331
				exit_nicely();
2332 2333 2334 2335 2336
			}

			n = PQntuples(res2);
			if (n != 1)
			{
2337 2338
				write_msg(NULL, "query to obtain name of primary key of table \"%s\" did not return exactly one result\n",
						  tblinfo[i].relname);
2339
				exit_nicely();
2340 2341
			}

2342 2343 2344
			/* Sanity check on LOJ */
			if (PQgetisnull(res2, 0, 0))
			{
2345 2346
				write_msg(NULL, "name of primary key of table \"%s\" returned NULL value\n",
						  tblinfo[i].relname);
2347
				exit_nicely();
2348 2349
			}

2350 2351 2352 2353
			tblinfo[i].primary_key_name =
				strdup(fmtId(PQgetvalue(res2, 0, 0), force_quotes));
			if (tblinfo[i].primary_key_name == NULL)
			{
2354
				write_msg(NULL, "out of memory\n");
2355
				exit_nicely();
2356 2357 2358 2359 2360
			}
		}
		else
			tblinfo[i].primary_key_name = NULL;

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

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

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

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

2437 2438
				tgname = PQgetvalue(res2, i2, i_tgname);

2439
				if (strcmp(PQgetvalue(res2, i2, i_tgisconstraint), "f") == 0)
2440
					tgisconstraint = 0;
2441
				else
2442
					tgisconstraint = 1;
2443 2444

				if (strcmp(PQgetvalue(res2, i2, i_tgdeferrable), "f") == 0)
2445
					tgdeferrable = 0;
2446
				else
2447
					tgdeferrable = 1;
2448 2449

				if (strcmp(PQgetvalue(res2, i2, i_tginitdeferred), "f") == 0)
2450
					tginitdeferred = 0;
2451
				else
2452
					tginitdeferred = 1;
2453

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

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

					/*
					 * 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)
					{
2483 2484
						write_msg(NULL, "query to obtain procedure name for trigger \"%s\" failed: %s",
								  tgname, PQerrorMessage(g_conn));
2485
						exit_nicely();
2486 2487 2488 2489
					}

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

2497
					tgfunc = strdup(PQgetvalue(r, 0, PQfnumber(r, "proname")));
2498
					PQclear(r);
2499
				}
2500
				else
2501
					tgfunc = strdup(finfo[findx].proname);
B
Bruce Momjian 已提交
2502

2503
				appendPQExpBuffer(delqry, "DROP TRIGGER %s ", fmtId(tgname, force_quotes));
B
Bruce Momjian 已提交
2504
				appendPQExpBuffer(delqry, "ON %s;\n",
B
Bruce Momjian 已提交
2505
								fmtId(tblinfo[i].relname, force_quotes));
2506

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

2547
				if (tgisconstraint)
2548
				{
2549 2550 2551 2552 2553
					tgconstrrelid = PQgetvalue(res2, i2, i_tgconstrrelid);

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

						if (PQgetisnull(res2, i2, i_tgconstrrelname))
2554
						{
2555 2556
							write_msg(NULL, "query produced NULL referenced table name for trigger \"%s\" on table \"%s\" (oid was %s)\n",
									  tgname, tblinfo[i].relname, tgconstrrelid);
2557
							exit_nicely();
2558
						}
2559

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

2571 2572 2573
				}

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

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

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

				/*** Initialize trcomments and troids ***/
2617

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

2628 2629
				if (tgfunc)
					free(tgfunc);
V
Vadim B. Mikheev 已提交
2630 2631 2632 2633 2634
			}
			PQclear(res2);
		}
		else
			tblinfo[i].triggers = NULL;
2635

2636 2637 2638 2639 2640
	}

	PQclear(res);

	return tblinfo;
2641 2642 2643 2644 2645

}

/*
 * getInherits
2646
 *	  read all the inheritance information
2647 2648
 * from the system catalogs return them in the InhInfo* structure
 *
2649 2650
 * numInherits is set to the number of tables read in
 *
2651 2652
 *
 */
2653
InhInfo    *
2654 2655
getInherits(int *numInherits)
{
2656
	PGresult   *res;
2657 2658
	int			ntups;
	int			i;
2659 2660
	PQExpBuffer query = createPQExpBuffer();
	InhInfo    *inhinfo;
2661

2662
	int			i_inhrelid;
2663
	int			i_inhparent;
2664 2665 2666

	/* find all the inheritance information */

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

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

	ntups = PQntuples(res);

	*numInherits = ntups;

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

2684
	i_inhrelid = PQfnumber(res, "inhrelid");
2685 2686 2687 2688
	i_inhparent = PQfnumber(res, "inhparent");

	for (i = 0; i < ntups; i++)
	{
2689
		inhinfo[i].inhrelid = strdup(PQgetvalue(res, i, i_inhrelid));
2690 2691 2692 2693 2694
		inhinfo[i].inhparent = strdup(PQgetvalue(res, i, i_inhparent));
	}

	PQclear(res);
	return inhinfo;
2695 2696 2697 2698
}

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

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

B
Hi, all  
Bruce Momjian 已提交
2740
		resetPQExpBuffer(q);
2741 2742 2743 2744

		if (g_fout->remoteVersion < 70100)
		{
			/* Fake the LOJ below */
2745
			appendPQExpBuffer(q,
2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769
						"  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 已提交
2770
		res = PQexec(g_conn, q->data);
2771 2772 2773
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
2774
			write_msg(NULL, "query to get table columns failed: %s", PQerrorMessage(g_conn));
2775
			exit_nicely();
2776 2777 2778 2779
		}

		ntups = PQntuples(res);

B
Bruce,  
Bruce Momjian 已提交
2780
		i_attoid = PQfnumber(res, "attoid");
2781 2782
		i_attname = PQfnumber(res, "attname");
		i_typname = PQfnumber(res, "typname");
2783
		i_atttypmod = PQfnumber(res, "atttypmod");
2784
		i_attnotnull = PQfnumber(res, "attnotnull");
V
Vadim B. Mikheev 已提交
2785
		i_atthasdef = PQfnumber(res, "atthasdef");
2786
		i_atttypedefn = PQfnumber(res, "atttypedefn");
2787 2788

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

B
Bruce,  
Bruce Momjian 已提交
2811
			tblinfo[i].attoids[j] = strdup(PQgetvalue(res, j, i_attoid));
2812
			tblinfo[i].attnames[j] = strdup(PQgetvalue(res, j, i_attname));
2813
			tblinfo[i].atttypedefns[j] = strdup(PQgetvalue(res, j, i_atttypedefn));
2814
			tblinfo[i].typnames[j] = strdup(PQgetvalue(res, j, i_typname));
2815
			tblinfo[i].atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
2816 2817
			tblinfo[i].inhAttrs[j] = 0; /* this flag is set in
										 * flagInhAttrs() */
2818 2819 2820
			tblinfo[i].inhAttrDef[j] = 0;
			tblinfo[i].inhNotNull[j] = 0;

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

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

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

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

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


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

	int			i_indexrelname;
	int			i_indrelname;
	int			i_indamname;
	int			i_indproc;
	int			i_indkey;
	int			i_indclass;
	int			i_indisunique;
2889
	int			i_indoid;
2890 2891
	int			i_oid;
	int			i_indisprimary;
2892
	int			i_indpred;
2893 2894

	/*
2895
	 * find all the user-defined indexes.
2896
	 *
2897
	 * Notice we skip indexes on system classes
2898 2899
	 *
	 * this is a 4-way join !!
2900 2901
	 *
	 * XXXX: Use LOJ
2902 2903
	 */

B
Hi, all  
Bruce Momjian 已提交
2904
	appendPQExpBuffer(query,
2905
					  "SELECT i.oid, t1.oid as indoid, t1.relname as indexrelname, t2.relname as indrelname, "
2906
					  "i.indproc, i.indkey, i.indclass, "
2907
				  "a.amname as indamname, i.indisunique, i.indisprimary, i.indpred "
2908 2909 2910
					"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 "
2911
					  "and t2.relname !~ '^pg_' ",
2912
					  g_last_builtin_oid);
2913

2914 2915 2916
	if (g_fout->remoteVersion < 70100)
		appendPQExpBuffer(query, " and t2.relkind != 'l'");

B
Hi, all  
Bruce Momjian 已提交
2917
	res = PQexec(g_conn, query->data);
2918 2919 2920
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
2921
		write_msg(NULL, "query to obtain list of indexes failed: %s", PQerrorMessage(g_conn));
2922
		exit_nicely();
2923 2924 2925 2926
	}

	ntups = PQntuples(res);

2927
	*numIndexes = ntups;
2928 2929 2930

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

2931 2932
	memset((char *) indinfo, 0, ntups * sizeof(IndInfo));

2933
	i_oid = PQfnumber(res, "oid");
B
Bruce,  
Bruce Momjian 已提交
2934
	i_indoid = PQfnumber(res, "indoid");
2935 2936 2937 2938 2939 2940 2941
	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");
2942
	i_indisprimary = PQfnumber(res, "indisprimary");
2943
	i_indpred = PQfnumber(res, "indpred");
2944 2945 2946

	for (i = 0; i < ntups; i++)
	{
2947
		indinfo[i].oid = strdup(PQgetvalue(res, i, i_oid));
B
Bruce,  
Bruce Momjian 已提交
2948
		indinfo[i].indoid = strdup(PQgetvalue(res, i, i_indoid));
2949 2950 2951 2952
		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));
2953 2954 2955 2956 2957 2958
		parseNumericArray(PQgetvalue(res, i, i_indkey),
						  indinfo[i].indkey,
						  INDEX_MAX_KEYS);
		parseNumericArray(PQgetvalue(res, i, i_indclass),
						  indinfo[i].indclass,
						  INDEX_MAX_KEYS);
2959
		indinfo[i].indisunique = strdup(PQgetvalue(res, i, i_indisunique));
2960
		indinfo[i].indisprimary = strdup(PQgetvalue(res, i, i_indisprimary));
2961
		indinfo[i].indpred = strdup(PQgetvalue(res, i, i_indpred));
2962 2963 2964
	}
	PQclear(res);
	return indinfo;
2965 2966
}

B
Bruce,  
Bruce Momjian 已提交
2967
/*------------------------------------------------------------------
2968
 * dumpComments --
B
Bruce,  
Bruce Momjian 已提交
2969
 *
2970
 * This routine is used to dump any comments associated with the
B
Bruce,  
Bruce Momjian 已提交
2971 2972 2973 2974
 * 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
2975
 * addition, the routine takes the stdio FILE handle to which the
B
Bruce,  
Bruce Momjian 已提交
2976 2977 2978 2979
 * output should be written.
 *------------------------------------------------------------------
*/

T
Tom Lane 已提交
2980
static void
B
Bruce Momjian 已提交
2981
dumpComment(Archive *fout, const char *target, const char *oid)
2982
{
B
Bruce,  
Bruce Momjian 已提交
2983

2984
	PGresult   *res;
B
Bruce,  
Bruce Momjian 已提交
2985
	PQExpBuffer query;
2986
	int			i_description;
B
Bruce,  
Bruce Momjian 已提交
2987

2988 2989 2990 2991
	/* Comments are SCHEMA not data */
	if (dataOnly)
		return;

B
Bruce,  
Bruce Momjian 已提交
2992 2993 2994 2995 2996 2997 2998 2999 3000
	/*** 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);
3001 3002
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
3003 3004
		write_msg(NULL, "query to get comment on oid %s failed: %s",
				   oid, PQerrorMessage(g_conn));
3005
		exit_nicely();
B
Bruce,  
Bruce Momjian 已提交
3006 3007 3008 3009
	}

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

3010 3011
	if (PQntuples(res) != 0)
	{
B
Bruce,  
Bruce Momjian 已提交
3012
		i_description = PQfnumber(res, "description");
B
Bruce Momjian 已提交
3013
		resetPQExpBuffer(query);
3014
		appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
3015
		formatStringLiteral(query, PQgetvalue(res, 0, i_description), PASS_LFTAB);
3016
		appendPQExpBuffer(query, ";\n");
B
Bruce Momjian 已提交
3017

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

B
Bruce,  
Bruce Momjian 已提交
3021 3022 3023 3024 3025
	}

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

	PQclear(res);
3026

B
Bruce,  
Bruce Momjian 已提交
3027 3028 3029
}

/*------------------------------------------------------------------
3030
 * dumpDBComment --
B
Bruce,  
Bruce Momjian 已提交
3031
 *
3032 3033
 * 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 已提交
3034 3035 3036 3037 3038
 * to dump the schema of the database, then this is the first
 * statement issued.
 *------------------------------------------------------------------
*/

3039
void
B
Bruce Momjian 已提交
3040
dumpDBComment(Archive *fout)
3041
{
B
Bruce,  
Bruce Momjian 已提交
3042

3043
	PGresult   *res;
B
Bruce,  
Bruce Momjian 已提交
3044
	PQExpBuffer query;
3045
	int			i_oid;
B
Bruce,  
Bruce Momjian 已提交
3046 3047 3048 3049

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

	query = createPQExpBuffer();
3050
	appendPQExpBuffer(query, "SELECT oid FROM pg_database WHERE datname = ");
3051
	formatStringLiteral(query, PQdb(g_conn), CONV_ALL);
B
Bruce,  
Bruce Momjian 已提交
3052 3053 3054 3055

	/*** Execute query ***/

	res = PQexec(g_conn, query->data);
3056 3057
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
3058 3059
		write_msg(NULL, "query to get database oid failed: %s",
				   PQerrorMessage(g_conn));
3060
		exit_nicely();
B
Bruce,  
Bruce Momjian 已提交
3061 3062 3063 3064
	}

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

3065 3066
	if (PQntuples(res) != 0)
	{
B
Bruce,  
Bruce Momjian 已提交
3067 3068 3069 3070 3071 3072 3073 3074 3075
		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);
3076

B
Bruce,  
Bruce Momjian 已提交
3077 3078
}

3079 3080
/*
 * dumpTypes
3081
 *	  writes out to fout the queries to recreate all the user-defined types
3082 3083 3084
 *
 */
void
B
Bruce Momjian 已提交
3085
dumpTypes(Archive *fout, FuncInfo *finfo, int numFuncs,
3086
		  TypeInfo *tinfo, int numTypes)
3087
{
3088
	int			i;
3089
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3090
	PQExpBuffer delq = createPQExpBuffer();
3091
	int			funcInd;
3092 3093 3094 3095
	const char *((*deps)[]);
	int			depIdx = 0;

	deps = malloc(sizeof(char*) * 10);
3096 3097 3098 3099 3100

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

		/* skip all the builtin types */
3101
		if (atooid(tinfo[i].oid) <= g_last_builtin_oid)
3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118
			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)
3119 3120
		{
			(*deps)[depIdx++] = strdup(finfo[funcInd].oid);
3121
			dumpOneFunc(fout, finfo, funcInd, tinfo, numTypes);
3122
		}
3123 3124 3125

		funcInd = findFuncByName(finfo, numFuncs, tinfo[i].typoutput);
		if (funcInd != -1)
3126 3127
		{
			(*deps)[depIdx++] = strdup(finfo[funcInd].oid);
3128
			dumpOneFunc(fout, finfo, funcInd, tinfo, numTypes);
3129
		}
3130

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

B
Hi, all  
Bruce Momjian 已提交
3133 3134
		resetPQExpBuffer(q);
		appendPQExpBuffer(q,
3135
						  "CREATE TYPE %s "
3136
						  "( internallength = %s, externallength = %s,",
3137 3138
						  fmtId(tinfo[i].typname, force_quotes),
						  tinfo[i].typlen,
3139 3140 3141 3142 3143 3144 3145 3146 3147 3148
						  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));
3149
		formatStringLiteral(q, tinfo[i].typdefault, CONV_ALL);
3150 3151 3152

		if (tinfo[i].isArray)
		{
3153
			char	   *elemType;
3154

3155
			elemType = findTypeByOid(tinfo, numTypes, tinfo[i].typelem, zeroAsOpaque);
3156 3157
			if (elemType == NULL)
			{
3158
				write_msg(NULL, "notice: array type %s - type for elements (oid %s) is not dumped\n",
3159
						  tinfo[i].typname, tinfo[i].typelem);
3160 3161 3162 3163 3164
				resetPQExpBuffer(q);
				resetPQExpBuffer(delq);
				continue;
			}

3165
			appendPQExpBuffer(q, ", element = %s, delimiter = ", elemType);
3166
			formatStringLiteral(q, tinfo[i].typdelim, CONV_ALL);
3167 3168

			(*deps)[depIdx++] = strdup(tinfo[i].typelem);
3169 3170
		}
		if (tinfo[i].passedbyvalue)
B
Hi, all  
Bruce Momjian 已提交
3171
			appendPQExpBuffer(q, ",passedbyvalue);\n");
3172
		else
B
Hi, all  
Bruce Momjian 已提交
3173
			appendPQExpBuffer(q, ");\n");
3174

3175 3176 3177
		(*deps)[depIdx++] = NULL; /* End of List */

		ArchiveEntry(fout, tinfo[i].oid, tinfo[i].typname, "TYPE", deps,
B
Bruce Momjian 已提交
3178
				  q->data, delq->data, "", tinfo[i].usename, NULL, NULL);
B
Bruce,  
Bruce Momjian 已提交
3179 3180 3181 3182

		/*** Dump Type Comments ***/

		resetPQExpBuffer(q);
B
Bruce Momjian 已提交
3183 3184
		resetPQExpBuffer(delq);

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

B
Bruce Momjian 已提交
3188
		resetPQExpBuffer(q);
3189
	}
3190 3191
}

3192 3193
/*
 * dumpProcLangs
B
Bruce Momjian 已提交
3194
 *		  writes out to fout the queries to recreate user-defined procedural languages
3195 3196 3197
 *
 */
void
B
Bruce Momjian 已提交
3198
dumpProcLangs(Archive *fout, FuncInfo *finfo, int numFuncs,
B
Bruce Momjian 已提交
3199
			  TypeInfo *tinfo, int numTypes)
3200
{
3201 3202
	PGresult   *res;
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
3203 3204
	PQExpBuffer defqry = createPQExpBuffer();
	PQExpBuffer delqry = createPQExpBuffer();
3205
	int			ntups;
B
Bruce Momjian 已提交
3206
	int			i_oid;
3207 3208 3209 3210
	int			i_lanname;
	int			i_lanpltrusted;
	int			i_lanplcallfoid;
	int			i_lancompiler;
3211
	Oid			lanoid;
3212 3213 3214
	char	   *lanname;
	char	   *lancompiler;
	const char *lanplcallfoid;
3215 3216 3217
	int			i,
				fidx;

B
Bruce Momjian 已提交
3218
	appendPQExpBuffer(query, "SELECT oid, * FROM pg_language "
3219 3220
					  "WHERE lanispl "
					  "ORDER BY oid");
B
Hi, all  
Bruce Momjian 已提交
3221
	res = PQexec(g_conn, query->data);
3222 3223 3224
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
3225 3226
		write_msg(NULL, "query to obtain list of procedural languages failed: %s",
				   PQerrorMessage(g_conn));
3227
		exit_nicely();
3228 3229 3230
	}
	ntups = PQntuples(res);

B
Bruce Momjian 已提交
3231 3232 3233 3234
	i_lanname = PQfnumber(res, "lanname");
	i_lanpltrusted = PQfnumber(res, "lanpltrusted");
	i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
	i_lancompiler = PQfnumber(res, "lancompiler");
B
Bruce Momjian 已提交
3235
	i_oid = PQfnumber(res, "oid");
3236

B
Bruce Momjian 已提交
3237 3238
	for (i = 0; i < ntups; i++)
	{
3239
		lanoid = atooid(PQgetvalue(res, i, i_oid));
3240 3241 3242
		if (lanoid <= g_last_builtin_oid)
			continue;

3243
		lanplcallfoid = PQgetvalue(res, i, i_lanplcallfoid);
3244 3245


3246 3247 3248 3249 3250 3251 3252
		for (fidx = 0; fidx < numFuncs; fidx++)
		{
			if (!strcmp(finfo[fidx].oid, lanplcallfoid))
				break;
		}
		if (fidx >= numFuncs)
		{
3253 3254
			write_msg(NULL, "handler procedure for procedural language %s not found\n",
					   PQgetvalue(res, i, i_lanname));
3255
			exit_nicely();
3256 3257 3258 3259
		}

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

3260 3261
		lanname = PQgetvalue(res, i, i_lanname);
		lancompiler = PQgetvalue(res, i, i_lancompiler);
3262

3263
		appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE ");
3264
		formatStringLiteral(delqry, lanname, CONV_ALL);
3265
		appendPQExpBuffer(delqry, ";\n");
3266

3267 3268 3269
		appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE ",
						  (PQgetvalue(res, i, i_lanpltrusted)[0] == 't') ?
						  "TRUSTED " : "");
3270
		formatStringLiteral(defqry, lanname, CONV_ALL);
3271 3272
		appendPQExpBuffer(defqry, " HANDLER %s LANCOMPILER ",
						  fmtId(finfo[fidx].proname, force_quotes));
3273
		formatStringLiteral(defqry, lancompiler, CONV_ALL);
3274
		appendPQExpBuffer(defqry, ";\n");
3275

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

3279 3280
		resetPQExpBuffer(defqry);
		resetPQExpBuffer(delqry);
3281 3282 3283 3284 3285 3286
	}

	PQclear(res);

}

3287 3288
/*
 * dumpFuncs
3289
 *	  writes out to fout the queries to recreate all the user-defined functions
3290 3291 3292
 *
 */
void
B
Bruce Momjian 已提交
3293
dumpFuncs(Archive *fout, FuncInfo *finfo, int numFuncs,
3294
		  TypeInfo *tinfo, int numTypes)
3295
{
3296
	int			i;
3297 3298 3299

	for (i = 0; i < numFuncs; i++)
		dumpOneFunc(fout, finfo, i, tinfo, numTypes);
3300 3301 3302 3303
}

/*
 * dumpOneFunc:
3304 3305
 *	  dump out only one function,  the index of which is given in the third
 *	argument
3306 3307 3308
 *
 */

3309
static void
B
Bruce Momjian 已提交
3310
dumpOneFunc(Archive *fout, FuncInfo *finfo, int i,
3311
			TypeInfo *tinfo, int numTypes)
3312
{
3313
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3314 3315
	PQExpBuffer fn = createPQExpBuffer();
	PQExpBuffer delqry = createPQExpBuffer();
B
Bruce,  
Bruce Momjian 已提交
3316
	PQExpBuffer fnlist = createPQExpBuffer();
B
Bruce Momjian 已提交
3317
	int			j;
3318
	PQExpBuffer asPart = createPQExpBuffer();
3319
	char		func_lang[NAMEDATALEN + 1];
3320 3321 3322 3323
	PGresult   *res;
	int			nlangs;
	int			i_lanname;
	char		query[256];
3324

B
Bruce Momjian 已提交
3325 3326 3327 3328
	char	   *listSep;
	char	   *listSepComma = ",";
	char	   *listSepNone = "";
	char	   *rettypename;
3329

3330 3331 3332 3333 3334
	if (finfo[i].dumped)
		return;
	else
		finfo[i].dumped = 1;

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

3337 3338 3339 3340 3341
	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 已提交
3342
	{
3343
		write_msg(NULL, "query to get name of procedural language failed: %s", PQerrorMessage(g_conn));
3344
		exit_nicely();
B
Bruce Momjian 已提交
3345
	}
3346 3347 3348
	nlangs = PQntuples(res);

	if (nlangs != 1)
B
Bruce Momjian 已提交
3349
	{
3350
		write_msg(NULL, "procedural language for function %s not found\n", finfo[i].proname);
3351
		exit_nicely();
B
Bruce Momjian 已提交
3352 3353
	}

3354
	i_lanname = PQfnumber(res, "lanname");
3355

3356
	/*
B
Bruce Momjian 已提交
3357 3358
	 * See backend/commands/define.c for details of how the 'AS' clause is
	 * used.
3359 3360 3361
	 */
	if (strcmp(finfo[i].probin, "-") != 0)
	{
3362
		appendPQExpBuffer(asPart, "AS ");
3363
		formatStringLiteral(asPart, finfo[i].probin, CONV_ALL);
3364
		if (strcmp(finfo[i].prosrc, "-") != 0)
3365 3366
		{
			appendPQExpBuffer(asPart, ", ");
3367
			formatStringLiteral(asPart, finfo[i].prosrc, PASS_LFTAB);
3368
		}
3369 3370 3371 3372
	}
	else
	{
		if (strcmp(finfo[i].prosrc, "-") != 0)
3373 3374
		{
			appendPQExpBuffer(asPart, "AS ");
3375
			formatStringLiteral(asPart, finfo[i].prosrc, PASS_LFTAB);
3376
		}
3377 3378
	}

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

3381
	PQclear(res);
B
Bruce Momjian 已提交
3382

B
Bruce Momjian 已提交
3383 3384
	resetPQExpBuffer(fn);
	appendPQExpBuffer(fn, "%s (", fmtId(finfo[i].proname, force_quotes));
3385 3386
	for (j = 0; j < finfo[i].nargs; j++)
	{
B
Bruce Momjian 已提交
3387
		char	   *typname;
3388

3389
		typname = findTypeByOid(tinfo, numTypes, finfo[i].argtypes[j], zeroAsOpaque);
3390 3391
		if (typname == NULL)
		{
3392 3393
			write_msg(NULL, "WARNING: function \"%s\" not dumped\n",
					  finfo[i].proname);
3394

3395
			write_msg(NULL, "reason: data type name of argument %d (oid %s) not found\n",
3396
					   j, finfo[i].argtypes[j]);
3397 3398 3399 3400 3401 3402 3403 3404
			resetPQExpBuffer(q);
			resetPQExpBuffer(fn);
			resetPQExpBuffer(delqry);
			resetPQExpBuffer(fnlist);
			resetPQExpBuffer(asPart);
			return;
		}

B
Bruce Momjian 已提交
3405 3406 3407
		appendPQExpBuffer(fn, "%s%s",
						  (j > 0) ? "," : "",
						  typname);
B
Bruce,  
Bruce Momjian 已提交
3408
		appendPQExpBuffer(fnlist, "%s%s",
B
Bruce Momjian 已提交
3409 3410
						  (j > 0) ? "," : "",
						  typname);
3411
	}
B
Bruce Momjian 已提交
3412 3413 3414
	appendPQExpBuffer(fn, ")");

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

3417 3418 3419 3420
	rettypename = findTypeByOid(tinfo, numTypes, finfo[i].prorettype, zeroAsOpaque);

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

3424 3425
		write_msg(NULL, "reason: name of return data type (oid %s) not found\n",
				  finfo[i].prorettype);
B
Bruce Momjian 已提交
3426 3427 3428 3429 3430 3431
		resetPQExpBuffer(q);
		resetPQExpBuffer(fn);
		resetPQExpBuffer(delqry);
		resetPQExpBuffer(fnlist);
		resetPQExpBuffer(asPart);
		return;
3432 3433
	}

B
Bruce Momjian 已提交
3434
	resetPQExpBuffer(q);
B
Bruce Momjian 已提交
3435
	appendPQExpBuffer(q, "CREATE FUNCTION %s ", fn->data);
3436 3437
	appendPQExpBuffer(q, "RETURNS %s%s %s LANGUAGE ",
					  (finfo[i].retset) ? "SETOF " : "",
3438
					  rettypename,
3439
					  asPart->data);
3440
	formatStringLiteral(q, func_lang, CONV_ALL);
3441

B
Bruce Momjian 已提交
3442
	if (finfo[i].iscachable || finfo[i].isstrict)		/* OR in new attrs here */
3443
	{
3444 3445 3446
		appendPQExpBuffer(q, " WITH (");
		listSep = listSepNone;

B
Bruce Momjian 已提交
3447 3448
		if (finfo[i].iscachable)
		{
3449 3450 3451 3452
			appendPQExpBuffer(q, "%s iscachable", listSep);
			listSep = listSepComma;
		}

B
Bruce Momjian 已提交
3453 3454
		if (finfo[i].isstrict)
		{
3455 3456 3457 3458
			appendPQExpBuffer(q, "%s isstrict", listSep);
			listSep = listSepComma;
		}
		appendPQExpBuffer(q, " )");
3459 3460 3461 3462
	}

	appendPQExpBuffer(q, ";\n");

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

B
Bruce,  
Bruce Momjian 已提交
3466 3467 3468 3469 3470 3471 3472 3473
	/*** 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);

3474 3475 3476 3477
}

/*
 * dumpOprs
3478
 *	  writes out to fout the queries to recreate all the user-defined operators
3479 3480
 *
 */
3481
void
B
Bruce Momjian 已提交
3482
dumpOprs(Archive *fout, OprInfo *oprinfo, int numOperators,
3483
		 TypeInfo *tinfo, int numTypes)
3484
{
B
Bruce Momjian 已提交
3485
	int			i;
3486
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3487
	PQExpBuffer delq = createPQExpBuffer();
3488 3489 3490 3491 3492 3493 3494 3495
	PQExpBuffer leftarg = createPQExpBuffer();
	PQExpBuffer rightarg = createPQExpBuffer();
	PQExpBuffer commutator = createPQExpBuffer();
	PQExpBuffer negator = createPQExpBuffer();
	PQExpBuffer restrictor = createPQExpBuffer();
	PQExpBuffer join = createPQExpBuffer();
	PQExpBuffer sort1 = createPQExpBuffer();
	PQExpBuffer sort2 = createPQExpBuffer();
3496 3497 3498

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

B
Hi, all  
Bruce Momjian 已提交
3501 3502 3503 3504 3505 3506 3507 3508 3509
		resetPQExpBuffer(leftarg);
		resetPQExpBuffer(rightarg);
		resetPQExpBuffer(commutator);
		resetPQExpBuffer(negator);
		resetPQExpBuffer(restrictor);
		resetPQExpBuffer(join);
		resetPQExpBuffer(sort1);
		resetPQExpBuffer(sort2);

3510
		/* skip all the builtin oids */
3511
		if (atooid(oprinfo[i].oid) <= g_last_builtin_oid)
3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527
			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 已提交
3528 3529
			name = findTypeByOid(tinfo, numTypes,
								 oprinfo[i].oprleft, zeroAsOpaque);
3530 3531
			if (name == NULL)
			{
3532 3533 3534 3535
				write_msg(NULL, "WARNING: operator \"%s\" (oid %s) not dumped\n",
						  oprinfo[i].oprname, oprinfo[i].oid);
				write_msg(NULL, "reason: oprleft (oid %s) not found\n",
						  oprinfo[i].oprleft);
3536 3537
				continue;
			}
B
Bruce Momjian 已提交
3538
			appendPQExpBuffer(leftarg, ",\n\tLEFTARG = %s ", name);
3539
		}
3540

3541 3542 3543
		if (strcmp(oprinfo[i].oprkind, "l") == 0 ||
			strcmp(oprinfo[i].oprkind, "b") == 0)
		{
B
Bruce Momjian 已提交
3544 3545
			name = findTypeByOid(tinfo, numTypes,
								 oprinfo[i].oprright, zeroAsOpaque);
3546 3547
			if (name == NULL)
			{
3548 3549 3550 3551
				write_msg(NULL, "WARNING: operator \"%s\" (oid %s) not dumped\n",
						  oprinfo[i].oprname, oprinfo[i].oid);
				write_msg(NULL, "reason: oprright (oid %s) not found\n",
						  oprinfo[i].oprright);
3552 3553 3554
				continue;
			}
			appendPQExpBuffer(rightarg, ",\n\tRIGHTARG = %s ", name);
3555
		}
3556

B
Hi, all  
Bruce Momjian 已提交
3557
		if (!(strcmp(oprinfo[i].oprcom, "0") == 0))
3558 3559 3560 3561
		{
			name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprcom);
			if (name == NULL)
			{
3562 3563 3564 3565
				write_msg(NULL, "WARNING: operator \"%s\" (oid %s) not dumped\n",
						  oprinfo[i].oprname, oprinfo[i].oid);
				write_msg(NULL, "reason: oprcom (oid %s) not found\n",
						  oprinfo[i].oprcom);
3566 3567 3568 3569
				continue;
			}
			appendPQExpBuffer(commutator, ",\n\tCOMMUTATOR = %s ", name);
		}
3570

B
Hi, all  
Bruce Momjian 已提交
3571
		if (!(strcmp(oprinfo[i].oprnegate, "0") == 0))
3572 3573 3574 3575
		{
			name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprnegate);
			if (name == NULL)
			{
3576 3577 3578 3579
				write_msg(NULL, "WARNING: operator \"%s\" (oid %s) not dumped\n",
						  oprinfo[i].oprname, oprinfo[i].oid);
				write_msg(NULL, "reason: oprnegate (oid %s) not found\n",
						  oprinfo[i].oprnegate);
3580 3581 3582 3583
				continue;
			}
			appendPQExpBuffer(negator, ",\n\tNEGATOR = %s ", name);
		}
3584

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

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

B
Hi, all  
Bruce Momjian 已提交
3591
		if (!(strcmp(oprinfo[i].oprlsortop, "0") == 0))
3592
		{
B
Bruce Momjian 已提交
3593
			name = findOprByOid(oprinfo, numOperators, oprinfo[i].oprlsortop);
3594 3595
			if (name == NULL)
			{
3596 3597 3598 3599
				write_msg(NULL, "WARNING: operator \"%s\" (oid %s) not dumped\n",
						  oprinfo[i].oprname, oprinfo[i].oid);
				write_msg(NULL, "reason: oprlsortop (oid %s) not found\n",
						  oprinfo[i].oprlsortop);
3600 3601 3602 3603
				continue;
			}
			appendPQExpBuffer(sort1, ",\n\tSORT1 = %s ", name);
		}
3604

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

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

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

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

/*
 * dumpAggs
3648
 *	  writes out to fout the queries to create all the user-defined aggregates
3649 3650 3651
 *
 */
void
B
Bruce Momjian 已提交
3652
dumpAggs(Archive *fout, AggInfo *agginfo, int numAggs,
3653
		 TypeInfo *tinfo, int numTypes)
3654
{
B
Bruce Momjian 已提交
3655
	int			i;
3656
	PQExpBuffer q = createPQExpBuffer();
B
Bruce Momjian 已提交
3657 3658
	PQExpBuffer delq = createPQExpBuffer();
	PQExpBuffer aggSig = createPQExpBuffer();
3659
	PQExpBuffer details = createPQExpBuffer();
3660 3661 3662

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

3665
		resetPQExpBuffer(details);
B
Hi, all  
Bruce Momjian 已提交
3666

3667
		/* skip all the builtin oids */
3668 3669 3670 3671 3672 3673 3674 3675 3676
		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)
		{
3677 3678 3679
			write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
					  aggSig->data);

3680
			resetPQExpBuffer(q);
3681
			appendPQExpBuffer(q, "-- WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
3682 3683 3684
									aggSig->data);
			ArchiveEntry(fout, agginfo[i].oid, aggSig->data, "WARNING", NULL,
					q->data, "" /* Del */, "", agginfo[i].usename, NULL, NULL);
3685
			continue;
3686
		}
3687

3688 3689 3690
		name = findTypeByOid(tinfo, numTypes, agginfo[i].aggbasetype, zeroAsAny + useBaseTypeName);
		if (name == NULL)
		{
3691 3692 3693 3694 3695 3696 3697 3698 3699 3700
			write_msg(NULL, "WARNING: aggregate function \"%s\" (oid %s) not dumped\n",
					  agginfo[i].aggname, agginfo[i].oid);
			write_msg(NULL, "reason: aggbasetype (oid %s) not found\n",
					  agginfo[i].aggbasetype);

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

3705 3706 3707
		name = findTypeByOid(tinfo, numTypes, agginfo[i].aggtranstype, zeroAsOpaque + useBaseTypeName);
		if (name == NULL)
		{
3708 3709 3710 3711 3712 3713 3714 3715 3716 3717
			write_msg(NULL, "WARNING: aggregate function \"%s\" (oid %s) not dumped\n",
					  agginfo[i].aggname, agginfo[i].oid);
			write_msg(NULL, "reason: aggtranstype (oid %s) not found\n",
					  agginfo[i].aggtranstype);

			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "-- WARNING: aggregate function \"%s\" (oid %s) not dumped\n", agginfo[i].aggname, agginfo[i].oid);
			appendPQExpBuffer(q, "-- reason: aggtranstype (oid %s) not found\n", agginfo[i].aggtranstype);
			ArchiveEntry(fout, agginfo[i].oid, aggSig->data, "WARNING", NULL,
						 q->data, "" /* Del */, "", agginfo[i].usename, NULL, NULL);
3718 3719
			continue;
		}
3720 3721
		appendPQExpBuffer(details,
						  "SFUNC = %s, STYPE = %s",
3722
						  agginfo[i].aggtransfn, name);
3723

3724
		if (agginfo[i].agginitval)
3725 3726
		{
			appendPQExpBuffer(details, ", INITCOND = ");
3727
			formatStringLiteral(details, agginfo[i].agginitval, CONV_ALL);
3728
		}
3729

B
Hi, all  
Bruce Momjian 已提交
3730
		if (!(strcmp(agginfo[i].aggfinalfn, "-") == 0))
3731 3732
			appendPQExpBuffer(details, ", FINALFUNC = %s",
							  agginfo[i].aggfinalfn);
3733

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

B
Hi, all  
Bruce Momjian 已提交
3737
		resetPQExpBuffer(q);
3738
		appendPQExpBuffer(q, "CREATE AGGREGATE %s ( %s );\n",
3739
						  agginfo[i].aggname,
3740
						  details->data);
3741

B
Bruce Momjian 已提交
3742
		ArchiveEntry(fout, agginfo[i].oid, aggSig->data, "AGGREGATE", NULL,
B
Bruce Momjian 已提交
3743
				q->data, delq->data, "", agginfo[i].usename, NULL, NULL);
B
Bruce,  
Bruce Momjian 已提交
3744 3745 3746 3747

		/*** Dump Aggregate Comments ***/

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

3752
	}
3753 3754
}

3755 3756 3757 3758 3759
/*
 * These are some support functions to fix the acl problem of pg_dump
 *
 * Matthew C. Aycock 12/02/97
 */
3760 3761 3762

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

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

3781
	aclbuf[0] = '\0';
3782

B
Bruce Momjian 已提交
3783
	if (strchr(s, 'a'))
3784
		AddAcl(aclbuf, "INSERT");
3785

B
Bruce Momjian 已提交
3786
	if (strchr(s, 'w'))
3787
		AddAcl(aclbuf, "UPDATE,DELETE");
B
Bruce Momjian 已提交
3788 3789

	if (strchr(s, 'r'))
3790
		AddAcl(aclbuf, "SELECT");
3791

3792
	if (strchr(s, 'R'))
3793
		AddAcl(aclbuf, "RULE");
3794

3795 3796 3797
	/* Special-case when they're all there */
	if (strcmp(aclbuf, "INSERT,UPDATE,DELETE,SELECT,RULE") == 0)
		return strdup("ALL");
3798

3799
	return strdup(aclbuf);
3800
}
3801

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


B
Bruce Momjian 已提交
3821 3822
/*
 * dumpACL:
3823 3824
 *	  Write out grant/revoke information
 *	  Called for sequences and tables
B
Bruce Momjian 已提交
3825 3826
 */

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

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

B
Bruce Momjian 已提交
3842 3843 3844
	/*
	 * Allocate a larginsh buffer for the output SQL.
	 */
B
Bruce Momjian 已提交
3845
	sql = (char *) malloc(sSize);
B
Bruce Momjian 已提交
3846

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

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

3857 3858
	/* Scan comma-separated ACL items */
	for (tok = strtok(aclbuf, ","); tok != NULL; tok = strtok(NULL, ","))
3859
	{
3860

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

		/* User name is string up to = in tok */
		eqpos = strchr(tok, '=');
B
Bruce Momjian 已提交
3872
		if (!eqpos)
B
Bruce Momjian 已提交
3873
		{
3874 3875 3876
			write_msg(NULL, "could not parse ACL list ('%s') for relation %s\n",
					  acls, tbinfo.relname);
			exit_nicely();
B
Bruce Momjian 已提交
3877 3878
		}

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

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

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

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

B
Bruce Momjian 已提交
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 3969 3970 3971 3972 3973
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));
	}
}
3974

3975 3976
/*
 * dumpTables:
3977
 *	  write out to fout all the user-define tables
3978
 */
3979

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

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

4026 4027
	for (i = 0; i < numTables; i++)
	{
4028
		if (tblinfo[i].sequence)/* already dumped */
V
Vadim B. Mikheev 已提交
4029
			continue;
4030

4031
		if (!tablename || (!strcmp(tblinfo[i].relname, tablename)) || (strlen(tablename) == 0))
4032 4033
		{

4034 4035
			resetPQExpBuffer(delq);
			resetPQExpBuffer(q);
4036

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

4045 4046
			}
			else
4047
			{
4048
				reltypename = "TABLE";
4049
				objoid = tblinfo[i].oid;
4050 4051
				parentRels = tblinfo[i].parentRels;
				numParents = tblinfo[i].numParents;
B
Bruce Momjian 已提交
4052

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

4055 4056 4057 4058 4059 4060
				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)
4061
					{
4062 4063 4064 4065 4066
						/* Format properly if not first attr */
						if (actual_atts > 0)
							appendPQExpBuffer(q, ",\n\t");

						/* Attr name & type */
4067 4068 4069 4070 4071 4072 4073 4074
						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);
						}
4075 4076

						/* Default value */
4077
						if (tblinfo[i].adef_expr[j] != NULL && tblinfo[i].inhAttrDef[j] == 0)
4078
							appendPQExpBuffer(q, " DEFAULT %s",
B
Bruce Momjian 已提交
4079
											  tblinfo[i].adef_expr[j]);
4080 4081

						/* Not Null constraint */
4082
						if (tblinfo[i].notnull[j] && tblinfo[i].inhNotNull[j] == 0)
4083 4084 4085 4086
							appendPQExpBuffer(q, " NOT NULL");

						actual_atts++;
					}
4087
				}
B
Hi all  
Bruce Momjian 已提交
4088

4089 4090


4091 4092 4093 4094 4095 4096 4097
				/* 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 已提交
4098
									  tblinfo[i].check_expr[k]);
4099
				}
4100

4101 4102
				/* Primary Key */
				if (tblinfo[i].pkIndexOid != NULL)
4103
				{
B
Bruce Momjian 已提交
4104
					PQExpBuffer consDef;
4105 4106

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

4113
					if (k >= numIndexes)
4114
					{
4115 4116
						write_msg(NULL, "dumpTables(): failed sanity check, could not find index (%s) for primary key constraint\n",
								   tblinfo[i].pkIndexOid);
4117
						exit_nicely();
4118 4119 4120 4121
					}

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

B
Bruce Momjian 已提交
4122
					if ((actual_atts + tblinfo[i].ncheck) > 0)
4123
						appendPQExpBuffer(q, ",\n\t");
4124 4125 4126 4127

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

					destroyPQExpBuffer(consDef);
4128
				}
B
Bruce Momjian 已提交
4129

4130

4131
				appendPQExpBuffer(q, "\n)");
4132

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

4145 4146
				appendPQExpBuffer(q, ";\n");
			}
B
Bruce Momjian 已提交
4147

B
Bruce Momjian 已提交
4148 4149
			if (!dataOnly)
			{
4150

4151
				ArchiveEntry(fout, objoid, tblinfo[i].relname,
B
Bruce Momjian 已提交
4152 4153
							 reltypename, NULL, q->data, delq->data, "", tblinfo[i].usename,
							 NULL, NULL);
B
Bruce Momjian 已提交
4154

4155 4156 4157 4158
				if (!aclsSkip)
					dumpACL(fout, tblinfo[i]);

			}
4159

4160
			/* Dump Field Comments */
B
Bruce,  
Bruce Momjian 已提交
4161

4162 4163
			for (j = 0; j < tblinfo[i].numatts; j++)
			{
B
Bruce,  
Bruce Momjian 已提交
4164 4165 4166 4167 4168 4169
				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]);
			}
4170

B
Bruce,  
Bruce Momjian 已提交
4171
			/* Dump Table Comments */
4172

B
Bruce,  
Bruce Momjian 已提交
4173
			resetPQExpBuffer(q);
4174
			appendPQExpBuffer(q, "%s %s", reltypename, fmtId(tblinfo[i].relname, force_quotes));
B
Bruce,  
Bruce Momjian 已提交
4175
			dumpComment(fout, q->data, tblinfo[i].oid);
4176

4177 4178
		}
	}
4179 4180
}

B
Bruce Momjian 已提交
4181 4182
static PQExpBuffer
getPKconstraint(TableInfo *tblInfo, IndInfo *indInfo)
4183
{
B
Bruce Momjian 已提交
4184 4185
	PQExpBuffer pkBuf = createPQExpBuffer();
	int			k;
4186 4187

	appendPQExpBuffer(pkBuf, "Constraint %s Primary Key (",
B
Bruce Momjian 已提交
4188
					  tblInfo->primary_key_name);
4189 4190 4191

	for (k = 0; k < INDEX_MAX_KEYS; k++)
	{
4192 4193
		int			indkey;
		const char *attname;
4194 4195 4196 4197

		indkey = atoi(indInfo->indkey[k]);
		if (indkey == InvalidAttrNumber)
			break;
4198
		attname = getAttrName(indkey, tblInfo);
4199 4200

		appendPQExpBuffer(pkBuf, "%s%s",
B
Bruce Momjian 已提交
4201 4202
						  (k == 0) ? "" : ", ",
						  fmtId(attname, force_quotes));
4203 4204 4205 4206 4207 4208 4209
	}

	appendPQExpBuffer(pkBuf, ")");

	return pkBuf;
}

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
/*
 * 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";
	}
4239 4240
	write_msg(NULL, "getAttrName(): invalid column number %d for table %s\n",
			   attrnum, tblInfo->relname);
4241
	exit_nicely();
4242 4243 4244
	return NULL;				/* keep compiler quiet */
}

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

4263
	PQExpBuffer q = createPQExpBuffer(),
B
Bruce Momjian 已提交
4264
				delq = createPQExpBuffer(),
B
Hi, all  
Bruce Momjian 已提交
4265 4266
				id1 = createPQExpBuffer(),
				id2 = createPQExpBuffer();
4267
	PGresult   *res;
4268

4269
	for (i = 0; i < numIndexes; i++)
4270 4271
	{
		tableInd = findTableByName(tblinfo, numTables,
4272 4273 4274
								   indinfo[i].indrelname);
		if (tableInd < 0)
		{
4275 4276
			write_msg(NULL, "dumpIndexes(): failed sanity check, table %s was not found\n",
					   indinfo[i].indrelname);
4277
			exit_nicely();
4278
		}
4279

4280 4281 4282
		/* Handle PK indexes */
		if (strcmp(indinfo[i].indisprimary, "t") == 0)
		{
4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299
#if 0
			/* PK: Enable this code when ALTER TABLE supports PK constraints. */

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

			resetPQExpBuffer(attlist);

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

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

			destroyPQExpBuffer(consDef);
#endif
B
Bruce Momjian 已提交
4300 4301 4302 4303 4304

			/*
			 * Don't need to do anything else for this system-generated
			 * index
			 */
4305 4306 4307 4308
			continue;
		}


4309 4310 4311 4312
		if (strcmp(indinfo[i].indproc, "0") == 0)
			funcname = NULL;
		else
		{
B
Bruce Momjian 已提交
4313
			int			numFuncs;
4314 4315 4316 4317 4318 4319 4320

			/*
			 * 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 已提交
4321 4322
			resetPQExpBuffer(q);
			appendPQExpBuffer(q,
4323 4324 4325
							  "SELECT proname from pg_proc "
							  "where pg_proc.oid = '%s'::oid",
							  indinfo[i].indproc);
B
Hi, all  
Bruce Momjian 已提交
4326
			res = PQexec(g_conn, q->data);
4327 4328
			if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
			{
4329 4330
				write_msg(NULL, "query to get function name of oid %s failed: %s",
						  indinfo[i].indproc, PQerrorMessage(g_conn));
4331
				exit_nicely();
4332
			}
4333 4334 4335

			/* Sanity: Check we got only one tuple */
			numFuncs = PQntuples(res);
B
Bruce Momjian 已提交
4336 4337
			if (numFuncs != 1)
			{
4338 4339
				write_msg(NULL, "query to get function name of oid %s returned %d rows; expected 1\n",
						  indinfo[i].indproc, numFuncs);
4340
				exit_nicely();
4341 4342
			}

B
Bruce Momjian 已提交
4343
			funcname = strdup(PQgetvalue(res, 0, PQfnumber(res, "proname")));
4344 4345 4346 4347 4348 4349
			PQclear(res);
		}

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

4352 4353 4354
			indclass = atoi(indinfo[i].indclass[nclass]);
			if (indclass == 0)
				break;
B
Hi, all  
Bruce Momjian 已提交
4355 4356
			resetPQExpBuffer(q);
			appendPQExpBuffer(q,
4357 4358 4359
							  "SELECT opcname from pg_opclass "
							  "where pg_opclass.oid = '%u'::oid",
							  indclass);
B
Hi, all  
Bruce Momjian 已提交
4360
			res = PQexec(g_conn, q->data);
4361 4362
			if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
			{
4363 4364
				write_msg(NULL, "query to get operator class name of oid %u failed: %s",
						  indclass, PQerrorMessage(g_conn));
4365
				exit_nicely();
4366
			}
4367 4368 4369

			/* Sanity: Check we got only one tuple */
			numRows = PQntuples(res);
B
Bruce Momjian 已提交
4370 4371
			if (numRows != 1)
			{
4372 4373
				write_msg(NULL, "query to get operator class name of oid %u returned %d rows; expected 1\n",
						  indclass, numRows);
4374
				exit_nicely();
4375 4376
			}

B
Bruce Momjian 已提交
4377
			classname[nclass] = strdup(PQgetvalue(res, 0, PQfnumber(res, "opcname")));
4378 4379 4380 4381 4382
			PQclear(res);
		}

		if (funcname && nclass != 1)
		{
4383 4384
			write_msg(NULL, "There must be exactly one OpClass for functional index \"%s\".\n",
					  indinfo[i].indexrelname);
4385
			exit_nicely();
4386 4387 4388
		}

		/* convert attribute numbers into attribute list */
B
Hi, all  
Bruce Momjian 已提交
4389 4390
		resetPQExpBuffer(attlist);
		for (k = 0; k < INDEX_MAX_KEYS; k++)
4391
		{
4392 4393
			int			indkey;
			const char *attname;
4394 4395

			indkey = atoi(indinfo[i].indkey[k]);
B
Bruce Momjian 已提交
4396
			if (indkey == InvalidAttrNumber)
4397
				break;
4398
			attname = getAttrName(indkey, &tblinfo[tableInd]);
4399
			if (funcname)
B
Hi, all  
Bruce Momjian 已提交
4400
				appendPQExpBuffer(attlist, "%s%s",
4401 4402
								  (k == 0) ? "" : ", ",
								  fmtId(attname, force_quotes));
4403 4404 4405 4406
			else
			{
				if (k >= nclass)
				{
4407
					write_msg(NULL, "no operator class found for column \"%s\" of index \"%s\"\n",
4408
							attname, indinfo[i].indexrelname);
4409
					exit_nicely();
4410
				}
B
Hi, all  
Bruce Momjian 已提交
4411 4412 4413 4414 4415
				resetPQExpBuffer(id1);
				resetPQExpBuffer(id2);
				appendPQExpBuffer(id1, fmtId(attname, force_quotes));
				appendPQExpBuffer(id2, fmtId(classname[k], force_quotes));
				appendPQExpBuffer(attlist, "%s%s %s",
4416 4417
								  (k == 0) ? "" : ", ",
								  id1->data, id2->data);
4418 4419 4420 4421
				free(classname[k]);
			}
		}

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

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

B
Bruce Momjian 已提交
4432 4433
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "CREATE %s INDEX %s on %s using %s (",
B
Bruce Momjian 已提交
4434 4435 4436 4437
			  (strcmp(indinfo[i].indisunique, "t") == 0) ? "UNIQUE" : "",
							  id1->data,
							  id2->data,
							  indinfo[i].indamname);
4438 4439
			if (funcname)
			{
4440
				/* need 2 printf's here cuz fmtId has static return area */
B
Bruce Momjian 已提交
4441
				appendPQExpBuffer(q, " %s", fmtId(funcname, false));
4442
				appendPQExpBuffer(q, " (%s) %s )", attlist->data,
B
Bruce Momjian 已提交
4443
								  fmtId(classname[0], force_quotes));
4444 4445 4446 4447
				free(funcname);
				free(classname[0]);
			}
			else
4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481
				appendPQExpBuffer(q, " %s )", attlist->data);
				
			if (*indinfo[i].indpred) /* If there is an index predicate */
			{
				int numRows;
				PQExpBuffer pred = createPQExpBuffer();
				
				appendPQExpBuffer(pred, "SELECT pg_get_expr(indpred,indrelid) as pred FROM pg_index WHERE oid = %s",
								  indinfo[i].oid);
				res = PQexec(g_conn, pred->data);
				if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
				{
					fprintf(stderr, "dumpIndices(): SELECT (indpred) failed.  "
							"Explanation from backend: '%s'.\n",
							PQerrorMessage(g_conn));
					exit_nicely();
				}
	
				/* Sanity: Check we got only one tuple */
				numRows = PQntuples(res);
				if (numRows != 1)
				{
					fprintf(stderr, "dumpIndices(): SELECT (indpred) for index %s returned %d tuples. Expected 1.\n",
							indinfo[i].indrelname, numRows);
					exit_nicely();
				}
	
				appendPQExpBuffer(q, " WHERE %s",
								  PQgetvalue(res, 0, PQfnumber(res, "pred")));

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

4483 4484 4485 4486 4487
			/*
			 * 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 已提交
4488
			ArchiveEntry(fout, tblinfo[tableInd].oid, id1->data, "INDEX", NULL, q->data, delq->data,
B
Bruce Momjian 已提交
4489
						 "", tblinfo[tableInd].usename, NULL, NULL);
B
Bruce Momjian 已提交
4490

4491
			/* Dump Index Comments */
B
Bruce,  
Bruce Momjian 已提交
4492 4493 4494
			resetPQExpBuffer(q);
			appendPQExpBuffer(q, "INDEX %s", id1->data);
			dumpComment(fout, q->data, indinfo[i].indoid);
4495

4496 4497
		}
	}
4498 4499

}
4500

4501
/*
B
Bruce Momjian 已提交
4502
 * dumpTuples
4503 4504 4505 4506 4507
 *	  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
4508
 *	  in PostgreSQL.
4509 4510 4511 4512
 *
 * the attrmap passed in tells how to map the attributes copied in to the
 * attributes copied out
 */
4513
#ifdef NOT_USED
4514
void
4515
dumpTuples(PGresult *res, FILE *fout, int *attrmap)
4516
{
4517 4518 4519 4520
	int			j,
				k;
	int			m,
				n;
B
Bruce Momjian 已提交
4521
	char	  **outVals = NULL; /* values to copy out */
4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540

	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++)
			{
4541
				char	   *pval = outVals[k];
4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561

				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);
	}
4562
}
4563

4564
#endif
4565

4566 4567 4568 4569
/*
 * setMaxOid -
 * find the maximum oid and generate a COPY statement to set it
*/
4570

4571
static void
B
Bruce Momjian 已提交
4572
setMaxOid(Archive *fout)
4573
{
B
Bruce Momjian 已提交
4574 4575
	PGresult   *res;
	Oid			max_oid;
B
Bruce Momjian 已提交
4576
	char		sql[1024];
4577

4578
	res = PQexec(g_conn, "CREATE TEMPORARY TABLE pgdump_oid (dummy int4)");
4579 4580 4581
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
4582
		write_msg(NULL, "could not create pgdump_oid table: %s", PQerrorMessage(g_conn));
4583
		exit_nicely();
4584 4585
	}
	PQclear(res);
4586
	res = PQexec(g_conn, "INSERT INTO pgdump_oid VALUES (0)");
4587 4588 4589
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
4590
		write_msg(NULL, "could not insert into pgdump_oid table: %s", PQerrorMessage(g_conn));
4591
		exit_nicely();
4592 4593 4594 4595
	}
	max_oid = atol(PQoidStatus(res));
	if (max_oid == 0)
	{
4596
		write_msg(NULL, "inserted invalid oid\n");
4597
		exit_nicely();
4598 4599
	}
	PQclear(res);
4600
	res = PQexec(g_conn, "DROP TABLE pgdump_oid;");
4601 4602 4603
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
4604
		write_msg(NULL, "could not drop pgdump_oid table: %s", PQerrorMessage(g_conn));
4605
		exit_nicely();
4606 4607 4608
	}
	PQclear(res);
	if (g_verbose)
4609
		write_msg(NULL, "maximum system oid is %u\n", max_oid);
4610 4611 4612 4613 4614 4615 4616
	snprintf(sql, 1024,
			 "CREATE TEMPORARY TABLE pgdump_oid (dummy int4);\n"
			 "COPY pgdump_oid WITH OIDS FROM stdin;\n"
			 "%-d\t0\n"
			 "\\.\n"
			 "DROP TABLE pgdump_oid;\n",
			 max_oid);
B
Bruce Momjian 已提交
4617

4618
	ArchiveEntry(fout, "0", "Max OID", "<Init>", NULL, sql, "", "", "", NULL, NULL);
4619
}
4620 4621 4622

/*
 * findLastBuiltInOid -
4623
 * find the last built in oid
4624 4625
 * we do this by retrieving datlastsysoid from the pg_database entry for this database,
 */
4626

4627
static Oid
4628
findLastBuiltinOid_V71(const char *dbname)
4629
{
B
Bruce Momjian 已提交
4630
	PGresult   *res;
4631
	int			ntups;
4632
	Oid			last_oid;
4633 4634 4635
	PQExpBuffer query = createPQExpBuffer();

	resetPQExpBuffer(query);
4636
	appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
4637
	formatStringLiteral(query, dbname, CONV_ALL);
4638

4639
	res = PQexec(g_conn, query->data);
4640 4641 4642
	if (res == NULL ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
4643
		write_msg(NULL, "error in finding the last system oid: %s", PQerrorMessage(g_conn));
4644
		exit_nicely();
4645 4646
	}
	ntups = PQntuples(res);
4647
	if (ntups < 1)
4648
	{
4649
		write_msg(NULL, "missing pg_database entry for this database\n");
4650
		exit_nicely();
4651 4652 4653
	}
	if (ntups > 1)
	{
4654
		write_msg(NULL, "found more than one pg_database entry for this database\n");
4655
		exit_nicely();
4656
	}
4657
	last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
4658 4659
	PQclear(res);
	return last_oid;
4660 4661
}

4662 4663 4664 4665 4666 4667 4668
/*
 * 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
*/

4669
static Oid
4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680
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)
	{
4681
		write_msg(NULL, "error in finding the template1 database: %s", PQerrorMessage(g_conn));
4682
		exit_nicely();
4683 4684 4685 4686
	}
	ntups = PQntuples(res);
	if (ntups < 1)
	{
4687
		write_msg(NULL, "could not find template1 database entry in the pg_database table\n");
4688
		exit_nicely();
4689 4690 4691
	}
	if (ntups > 1)
	{
4692
		write_msg(NULL, "found more than one template1 database entry in the pg_database table\n");
4693
		exit_nicely();
4694 4695 4696 4697 4698
	}
	last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
	PQclear(res);
	return last_oid;
}
4699

4700
static void
4701
dumpSequence(Archive *fout, TableInfo tbinfo, const bool schemaOnly, const bool dataOnly)
4702
{
4703
	PGresult   *res;
B
Bruce Momjian 已提交
4704
	int4		last,
4705 4706 4707 4708
				incby,
				maxv,
				minv,
				cache;
B
Bruce Momjian 已提交
4709
	char		cycled,
B
Bruce Momjian 已提交
4710
				called;
4711 4712
	const char *t;
	PQExpBuffer query = createPQExpBuffer();
B
Bruce Momjian 已提交
4713
	PQExpBuffer delqry = createPQExpBuffer();
4714

B
Hi, all  
Bruce Momjian 已提交
4715
	appendPQExpBuffer(query,
4716
			"SELECT sequence_name, last_value, increment_by, max_value, "
4717 4718
				  "min_value, cache_value, is_cycled, is_called from %s",
					  fmtId(tbinfo.relname, force_quotes));
4719

B
Hi, all  
Bruce Momjian 已提交
4720
	res = PQexec(g_conn, query->data);
4721 4722
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
4723
		write_msg(NULL, "query to get data of sequence \"%s\" failed: %s", tbinfo.relname, PQerrorMessage(g_conn));
4724
		exit_nicely();
4725 4726 4727 4728
	}

	if (PQntuples(res) != 1)
	{
4729 4730
		write_msg(NULL, "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
				   tbinfo.relname, PQntuples(res));
4731
		exit_nicely();
4732 4733 4734 4735
	}

	if (strcmp(PQgetvalue(res, 0, 0), tbinfo.relname) != 0)
	{
4736 4737
		write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
				   tbinfo.relname, PQgetvalue(res, 0, 0));
4738
		exit_nicely();
4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751
	}


	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;

4752
	/*
B
Bruce Momjian 已提交
4753 4754
	 * The logic we use for restoring sequences is as follows: -   Add a
	 * basic CREATE SEQUENCE statement (use last_val for start if called
4755 4756 4757 4758
	 * with 'f', else use min_val for start_val).
	 *
	 *	Add a 'SETVAL(seq, last_val, iscalled)' at restore-time iff
	 *  we load data
4759
	 */
4760

4761 4762 4763
	if (!dataOnly)
	{
		PQclear(res);
4764

4765 4766
		resetPQExpBuffer(delqry);
		appendPQExpBuffer(delqry, "DROP SEQUENCE %s;\n", fmtId(tbinfo.relname, force_quotes));
4767

4768 4769
		resetPQExpBuffer(query);
		appendPQExpBuffer(query,
B
Bruce Momjian 已提交
4770
				  "CREATE SEQUENCE %s start %d increment %d maxvalue %d "
4771
						  "minvalue %d  cache %d %s;\n",
B
Bruce Momjian 已提交
4772
						  fmtId(tbinfo.relname, force_quotes),
4773 4774 4775 4776
						  (called == 't') ? minv : last,
						  incby, maxv, minv, cache,
						  (cycled == 't') ? "cycle" : "");

P
Philip Warner 已提交
4777
		ArchiveEntry(fout, tbinfo.oid, tbinfo.relname, "SEQUENCE", NULL,
B
Bruce Momjian 已提交
4778
			  query->data, delqry->data, "", tbinfo.usename, NULL, NULL);
4779
	}
4780

4781 4782 4783 4784 4785 4786
	if (!schemaOnly)
	{
		resetPQExpBuffer(query);
		appendPQExpBuffer(query, "SELECT setval (");
		formatStringLiteral(query, fmtId(tbinfo.relname, force_quotes), CONV_ALL);
		appendPQExpBuffer(query, ", %d, '%c');\n", last, called);
4787

P
Philip Warner 已提交
4788
		ArchiveEntry(fout, tbinfo.oid, tbinfo.relname, "SEQUENCE SET", NULL,
B
Bruce Momjian 已提交
4789
					 query->data, "" /* Del */ , "", "", NULL, NULL);
4790
	}
B
Bruce,  
Bruce Momjian 已提交
4791

4792 4793 4794
	if (!dataOnly)
	{
		/* Dump Sequence Comments */
B
Bruce,  
Bruce Momjian 已提交
4795

4796 4797 4798 4799
		resetPQExpBuffer(query);
		appendPQExpBuffer(query, "SEQUENCE %s", fmtId(tbinfo.relname, force_quotes));
		dumpComment(fout, query->data, tbinfo.oid);
	}
4800
}
V
Vadim B. Mikheev 已提交
4801 4802


4803
static void
B
Bruce Momjian 已提交
4804
dumpTriggers(Archive *fout, const char *tablename,
4805
			 TableInfo *tblinfo, int numTables)
V
Vadim B. Mikheev 已提交
4806
{
4807 4808 4809
	int			i,
				j;

V
Vadim B. Mikheev 已提交
4810
	if (g_verbose)
4811
		write_msg(NULL, "dumping out triggers\n");
4812

V
Vadim B. Mikheev 已提交
4813 4814
	for (i = 0; i < numTables; i++)
	{
B
Bruce Momjian 已提交
4815
		if (tablename && (strcmp(tblinfo[i].relname, tablename) != 0) && (strlen(tablename) > 0))
V
Vadim B. Mikheev 已提交
4816
			continue;
4817

V
Vadim B. Mikheev 已提交
4818 4819
		for (j = 0; j < tblinfo[i].ntrig; j++)
		{
B
Bruce Momjian 已提交
4820
			ArchiveEntry(fout, tblinfo[i].triggers[j].oid, tblinfo[i].triggers[j].tgname,
B
Bruce Momjian 已提交
4821 4822
				   "TRIGGER", NULL, tblinfo[i].triggers[j].tgsrc, "", "",
						 tblinfo[i].usename, NULL, NULL);
B
Bruce Momjian 已提交
4823
			dumpComment(fout, tblinfo[i].triggers[j].tgcomment, tblinfo[i].triggers[j].oid);
V
Vadim B. Mikheev 已提交
4824 4825 4826
		}
	}
}
4827 4828


4829
static void
B
Bruce Momjian 已提交
4830
dumpRules(Archive *fout, const char *tablename,
B
Bruce Momjian 已提交
4831
		  TableInfo *tblinfo, int numTables)
4832
{
B
Bruce Momjian 已提交
4833 4834 4835 4836
	PGresult   *res;
	int			nrules;
	int			i,
				t;
4837
	PQExpBuffer query = createPQExpBuffer();
4838

B
Bruce Momjian 已提交
4839
	int			i_definition;
4840
	int			i_oid;
4841
	int			i_owner;
4842
	int			i_rulename;
4843 4844

	if (g_verbose)
4845
		write_msg(NULL, "dumping out rules\n");
4846 4847 4848 4849 4850 4851

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

		/*
B
Bruce Momjian 已提交
4856 4857
		 * 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).
4858 4859
		 *
		 * XXXX: Use LOJ here
4860
		 */
B
Hi, all  
Bruce Momjian 已提交
4861
		resetPQExpBuffer(query);
4862
		appendPQExpBuffer(query, "SELECT definition,"
4863
						  "   (select usename from pg_user where pg_class.relowner = usesysid) AS viewowner, "
4864 4865
						  "   pg_rewrite.oid, pg_rewrite.rulename "
						  "FROM pg_rewrite, pg_class, pg_rules "
4866
						  "WHERE pg_class.relname = ");
4867
		formatStringLiteral(query, tblinfo[t].relname, CONV_ALL);
4868
		appendPQExpBuffer(query,
4869 4870
						  "    AND pg_rewrite.ev_class = pg_class.oid "
						  "    AND pg_rules.tablename = pg_class.relname "
B
Bruce Momjian 已提交
4871
					   "    AND pg_rules.rulename = pg_rewrite.rulename "
4872
						  "ORDER BY pg_rewrite.oid");
B
Hi, all  
Bruce Momjian 已提交
4873
		res = PQexec(g_conn, query->data);
4874 4875 4876
		if (!res ||
			PQresultStatus(res) != PGRES_TUPLES_OK)
		{
4877 4878
			write_msg(NULL, "query to get rules associated with table \"%s\" failed: %s",
					   tblinfo[t].relname, PQerrorMessage(g_conn));
4879
			exit_nicely();
4880 4881 4882 4883
		}

		nrules = PQntuples(res);
		i_definition = PQfnumber(res, "definition");
4884
		i_owner = PQfnumber(res, "viewowner");
B
Bruce,  
Bruce Momjian 已提交
4885 4886
		i_oid = PQfnumber(res, "oid");
		i_rulename = PQfnumber(res, "rulename");
4887 4888 4889 4890

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

4892 4893
		for (i = 0; i < nrules; i++)
		{
B
Bruce Momjian 已提交
4894
			ArchiveEntry(fout, PQgetvalue(res, i, i_oid), PQgetvalue(res, i, i_rulename),
B
Bruce Momjian 已提交
4895 4896
						 "RULE", NULL, PQgetvalue(res, i, i_definition),
						 "", "", PQgetvalue(res, i, i_owner), NULL, NULL);
4897

B
Bruce,  
Bruce Momjian 已提交
4898 4899 4900 4901 4902
			/* 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));
4903

B
Bruce,  
Bruce Momjian 已提交
4904 4905
		}

4906 4907 4908
		PQclear(res);
	}
}