ruleutils.c 81 KB
Newer Older
1
/**********************************************************************
2 3
 * ruleutils.c	- Functions to convert stored expressions/querytrees
 *				back to source text
4 5
 *
 * IDENTIFICATION
6
 *	  $Header: /cvsroot/pgsql/src/backend/utils/adt/ruleutils.c,v 1.116 2002/08/16 23:01:19 tgl Exp $
7
 *
8
 *	  This software is copyrighted by Jan Wieck - Hamburg.
9
 *
10 11 12 13 14 15 16 17 18 19
 *	  The author hereby grants permission  to  use,  copy,	modify,
 *	  distribute,  and	license this software and its documentation
 *	  for any purpose, provided that existing copyright notices are
 *	  retained	in	all  copies  and  that	this notice is included
 *	  verbatim in any distributions. No written agreement, license,
 *	  or  royalty  fee	is required for any of the authorized uses.
 *	  Modifications to this software may be  copyrighted  by  their
 *	  author  and  need  not  follow  the licensing terms described
 *	  here, provided that the new terms are  clearly  indicated  on
 *	  the first page of each file where they apply.
20
 *
21 22 23 24 25 26
 *	  IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY
 *	  PARTY  FOR  DIRECT,	INDIRECT,	SPECIAL,   INCIDENTAL,	 OR
 *	  CONSEQUENTIAL   DAMAGES  ARISING	OUT  OF  THE  USE  OF  THIS
 *	  SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN
 *	  IF  THE  AUTHOR  HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
 *	  DAMAGE.
27
 *
28 29 30 31 32 33 34
 *	  THE  AUTHOR  AND	DISTRIBUTORS  SPECIFICALLY	 DISCLAIM	ANY
 *	  WARRANTIES,  INCLUDING,  BUT	NOT  LIMITED  TO,  THE	IMPLIED
 *	  WARRANTIES  OF  MERCHANTABILITY,	FITNESS  FOR  A  PARTICULAR
 *	  PURPOSE,	AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON
 *	  AN "AS IS" BASIS, AND THE AUTHOR	AND  DISTRIBUTORS  HAVE  NO
 *	  OBLIGATION   TO	PROVIDE   MAINTENANCE,	 SUPPORT,  UPDATES,
 *	  ENHANCEMENTS, OR MODIFICATIONS.
35 36 37
 *
 **********************************************************************/

38 39
#include "postgres.h"

40 41 42
#include <unistd.h>
#include <fcntl.h>

43 44
#include "access/genam.h"
#include "catalog/catname.h"
45
#include "catalog/heap.h"
46
#include "catalog/index.h"
47
#include "catalog/indexing.h"
48
#include "catalog/namespace.h"
49
#include "catalog/pg_cast.h"
50
#include "catalog/pg_constraint.h"
51
#include "catalog/pg_index.h"
52
#include "catalog/pg_opclass.h"
53 54
#include "catalog/pg_operator.h"
#include "catalog/pg_shadow.h"
55 56
#include "executor/spi.h"
#include "lib/stringinfo.h"
57
#include "nodes/makefuncs.h"
58 59
#include "optimizer/clauses.h"
#include "optimizer/tlist.h"
60
#include "parser/keywords.h"
61
#include "parser/parse_expr.h"
62 63
#include "parser/parse_func.h"
#include "parser/parse_oper.h"
64
#include "parser/parsetree.h"
65
#include "rewrite/rewriteManip.h"
66
#include "rewrite/rewriteSupport.h"
67 68
#include "utils/array.h"
#include "utils/fmgroids.h"
69
#include "utils/lsyscache.h"
70 71


72 73 74 75
/* ----------
 * Local data types
 * ----------
 */
76 77

/* Context info needed for invoking a recursive querytree display routine */
78
typedef struct
Bruce Momjian's avatar
Bruce Momjian committed
79
{
80
	StringInfo	buf;			/* output buffer to append to */
81
	List	   *namespaces;		/* List of deparse_namespace nodes */
82 83
	bool		varprefix;		/* TRUE to print prefixes on Vars */
} deparse_context;
84

85 86
/*
 * Each level of query context around a subtree needs a level of Var namespace.
87 88 89 90 91 92 93 94
 * A Var having varlevelsup=N refers to the N'th item (counting from 0) in
 * the current context's namespaces list.
 *
 * The rangetable is the list of actual RTEs from the query tree.
 *
 * For deparsing plan trees, we allow two special RTE entries that are not
 * part of the rtable list (mainly because they don't have consecutively
 * allocated varnos).
95 96 97 98
 */
typedef struct
{
	List	   *rtable;			/* List of RangeTblEntry nodes */
99 100 101 102
	int			outer_varno;	/* varno for outer_rte */
	RangeTblEntry *outer_rte;	/* special RangeTblEntry, or NULL */
	int			inner_varno;	/* varno for inner_rte */
	RangeTblEntry *inner_rte;	/* special RangeTblEntry, or NULL */
103
} deparse_namespace;
104

105

106 107 108 109
/* ----------
 * Global data
 * ----------
 */
110
static void *plan_getrulebyoid = NULL;
111
static char *query_getrulebyoid = "SELECT * FROM pg_catalog.pg_rewrite WHERE oid = $1";
112
static void *plan_getviewrule = NULL;
113
static char *query_getviewrule = "SELECT * FROM pg_catalog.pg_rewrite WHERE ev_class = $1 AND rulename = $2";
114 115 116 117


/* ----------
 * Local functions
118 119 120 121
 *
 * Most of these functions used to use fixed-size buffers to build their
 * results.  Now, they take an (already initialized) StringInfo object
 * as a parameter, and append their text output to its contents.
122 123
 * ----------
 */
124
static text *pg_do_getviewdef(Oid viewoid);
125 126
static void decompile_column_index_array(Datum column_index_array, Oid relId,
										 StringInfo buf);
127 128
static void make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc);
static void make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc);
129 130 131 132
static void get_query_def(Query *query, StringInfo buf, List *parentnamespace,
						  TupleDesc resultDesc);
static void get_select_query_def(Query *query, deparse_context *context,
								 TupleDesc resultDesc);
133 134 135
static void get_insert_query_def(Query *query, deparse_context *context);
static void get_update_query_def(Query *query, deparse_context *context);
static void get_delete_query_def(Query *query, deparse_context *context);
136
static void get_utility_query_def(Query *query, deparse_context *context);
137 138
static void get_basic_select_query(Query *query, deparse_context *context,
								   TupleDesc resultDesc);
139
static void get_setop_query(Node *setOp, Query *query,
140 141
							deparse_context *context,
							TupleDesc resultDesc);
142
static Node *get_rule_sortgroupclause(SortClause *srt, List *tlist,
143 144
						 bool force_colno,
						 deparse_context *context);
145
static void get_names_for_var(Var *var, deparse_context *context,
146 147 148
				  char **schemaname, char **refname, char **attname);
static RangeTblEntry *find_rte_by_refname(const char *refname,
										  deparse_context *context);
149
static void get_rule_expr(Node *node, deparse_context *context);
150
static void get_oper_expr(Expr *expr, deparse_context *context);
151
static void get_func_expr(Expr *expr, deparse_context *context);
152
static void get_agg_expr(Aggref *aggref, deparse_context *context);
153
static Node *strip_type_coercion(Node *expr, Oid resultType);
154 155 156
static void get_tle_expr(TargetEntry *tle, deparse_context *context);
static void get_const_expr(Const *constval, deparse_context *context);
static void get_sublink_expr(Node *node, deparse_context *context);
157 158
static void get_from_clause(Query *query, deparse_context *context);
static void get_from_clause_item(Node *jtnode, Query *query,
159
					 deparse_context *context);
160
static void get_opclass_name(Oid opclass, Oid actual_datatype,
161
				 StringInfo buf);
162
static bool tleIsArrayAssign(TargetEntry *tle);
163 164 165
static char *generate_relation_name(Oid relid);
static char *generate_function_name(Oid funcid, int nargs, Oid *argtypes);
static char *generate_operator_name(Oid operid, Oid arg1, Oid arg2);
166
static char *get_relid_attribute_name(Oid relid, AttrNumber attnum);
167

168
#define only_marker(rte)  ((rte)->inh ? "" : "ONLY ")
169

170 171 172 173 174 175 176

/* ----------
 * get_ruledef			- Do it all and return a text
 *				  that could be used as a statement
 *				  to recreate the rule
 * ----------
 */
177 178
Datum
pg_get_ruledef(PG_FUNCTION_ARGS)
179
{
180
	Oid			ruleoid = PG_GETARG_OID(0);
181 182
	text	   *ruledef;
	Datum		args[1];
183
	char		nulls[1];
184 185 186
	int			spirc;
	HeapTuple	ruletup;
	TupleDesc	rulettc;
187
	StringInfoData buf;
188 189
	int			len;

190
	/*
191 192 193 194 195
	 * Connect to SPI manager
	 */
	if (SPI_connect() != SPI_OK_CONNECT)
		elog(ERROR, "get_ruledef: cannot connect to SPI manager");

196
	/*
197 198 199
	 * On the first call prepare the plan to lookup pg_rewrite. We read
	 * pg_rewrite over the SPI manager instead of using the syscache to be
	 * checked for read access on pg_rewrite.
200
	 */
201
	if (plan_getrulebyoid == NULL)
202 203 204 205
	{
		Oid			argtypes[1];
		void	   *plan;

206 207
		argtypes[0] = OIDOID;
		plan = SPI_prepare(query_getrulebyoid, 1, argtypes);
208
		if (plan == NULL)
209 210
			elog(ERROR, "SPI_prepare() failed for \"%s\"", query_getrulebyoid);
		plan_getrulebyoid = SPI_saveplan(plan);
211 212
	}

213
	/*
214 215
	 * Get the pg_rewrite tuple for this rule
	 */
216 217 218
	args[0] = ObjectIdGetDatum(ruleoid);
	nulls[0] = ' ';
	spirc = SPI_execp(plan_getrulebyoid, args, nulls, 1);
219
	if (spirc != SPI_OK_SELECT)
220
		elog(ERROR, "failed to get pg_rewrite tuple for %u", ruleoid);
221 222 223 224
	if (SPI_processed != 1)
	{
		if (SPI_finish() != SPI_OK_FINISH)
			elog(ERROR, "get_ruledef: SPI_finish() failed");
225
		ruledef = palloc(VARHDRSZ + 1);
Jan Wieck's avatar
TOAST  
Jan Wieck committed
226
		VARATT_SIZEP(ruledef) = VARHDRSZ + 1;
227
		VARDATA(ruledef)[0] = '-';
228
		PG_RETURN_TEXT_P(ruledef);
229 230 231 232 233
	}

	ruletup = SPI_tuptable->vals[0];
	rulettc = SPI_tuptable->tupdesc;

234
	/*
235 236
	 * Get the rules definition and put it into executors memory
	 */
237 238 239
	initStringInfo(&buf);
	make_ruledef(&buf, ruletup, rulettc);
	len = buf.len + VARHDRSZ;
240
	ruledef = SPI_palloc(len);
Jan Wieck's avatar
TOAST  
Jan Wieck committed
241
	VARATT_SIZEP(ruledef) = len;
242 243
	memcpy(VARDATA(ruledef), buf.data, buf.len);
	pfree(buf.data);
244

245
	/*
246 247 248 249 250
	 * Disconnect from SPI manager
	 */
	if (SPI_finish() != SPI_OK_FINISH)
		elog(ERROR, "get_ruledef: SPI_finish() failed");

251
	/*
252 253
	 * Easy - isn't it?
	 */
254
	PG_RETURN_TEXT_P(ruledef);
255 256 257 258 259 260 261 262
}


/* ----------
 * get_viewdef			- Mainly the same thing, but we
 *				  only return the SELECT part of a view
 * ----------
 */
263 264
Datum
pg_get_viewdef(PG_FUNCTION_ARGS)
265
{
266 267
	/* By OID */
	Oid			viewoid = PG_GETARG_OID(0);
268
	text	   *ruledef;
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299

	ruledef = pg_do_getviewdef(viewoid);
	PG_RETURN_TEXT_P(ruledef);
}

Datum
pg_get_viewdef_name(PG_FUNCTION_ARGS)
{
	/* By qualified name */
	text	   *viewname = PG_GETARG_TEXT_P(0);
	RangeVar   *viewrel;
	Oid			viewoid;
	text	   *ruledef;

	viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname,
															   "get_viewdef"));
	viewoid = RangeVarGetRelid(viewrel, false);

	ruledef = pg_do_getviewdef(viewoid);
	PG_RETURN_TEXT_P(ruledef);
}

/*
 * Common code for by-OID and by-name variants of pg_get_viewdef
 */
static text *
pg_do_getviewdef(Oid viewoid)
{
	text	   *ruledef;
	Datum		args[2];
	char		nulls[2];
300 301 302
	int			spirc;
	HeapTuple	ruletup;
	TupleDesc	rulettc;
303
	StringInfoData buf;
304 305
	int			len;

306
	/*
307 308 309 310 311
	 * Connect to SPI manager
	 */
	if (SPI_connect() != SPI_OK_CONNECT)
		elog(ERROR, "get_viewdef: cannot connect to SPI manager");

312
	/*
313 314 315
	 * On the first call prepare the plan to lookup pg_rewrite. We read
	 * pg_rewrite over the SPI manager instead of using the syscache to be
	 * checked for read access on pg_rewrite.
316
	 */
317
	if (plan_getviewrule == NULL)
318
	{
319
		Oid			argtypes[2];
320 321
		void	   *plan;

322 323 324
		argtypes[0] = OIDOID;
		argtypes[1] = NAMEOID;
		plan = SPI_prepare(query_getviewrule, 2, argtypes);
325
		if (plan == NULL)
326 327
			elog(ERROR, "SPI_prepare() failed for \"%s\"", query_getviewrule);
		plan_getviewrule = SPI_saveplan(plan);
328 329
	}

330
	/*
331
	 * Get the pg_rewrite tuple for the view's SELECT rule
332
	 */
333
	args[0] = ObjectIdGetDatum(viewoid);
334
	args[1] = PointerGetDatum(ViewSelectRuleName);
335
	nulls[0] = ' ';
336 337
	nulls[1] = ' ';
	spirc = SPI_execp(plan_getviewrule, args, nulls, 2);
338
	if (spirc != SPI_OK_SELECT)
339
		elog(ERROR, "failed to get pg_rewrite tuple for view %u", viewoid);
340
	initStringInfo(&buf);
341
	if (SPI_processed != 1)
342
		appendStringInfo(&buf, "Not a view");
343 344
	else
	{
345
		/*
346 347 348 349
		 * Get the rules definition and put it into executors memory
		 */
		ruletup = SPI_tuptable->vals[0];
		rulettc = SPI_tuptable->tupdesc;
350
		make_viewdef(&buf, ruletup, rulettc);
351
	}
352
	len = buf.len + VARHDRSZ;
353
	ruledef = SPI_palloc(len);
Jan Wieck's avatar
TOAST  
Jan Wieck committed
354
	VARATT_SIZEP(ruledef) = len;
355 356
	memcpy(VARDATA(ruledef), buf.data, buf.len);
	pfree(buf.data);
357

358
	/*
359 360 361 362 363
	 * Disconnect from SPI manager
	 */
	if (SPI_finish() != SPI_OK_FINISH)
		elog(ERROR, "get_viewdef: SPI_finish() failed");

364
	return ruledef;
365 366 367
}


368
/* ----------
369
 * get_indexdef			- Get the definition of an index
370 371
 * ----------
 */
372 373
Datum
pg_get_indexdef(PG_FUNCTION_ARGS)
374
{
375
	Oid			indexrelid = PG_GETARG_OID(0);
Bruce Momjian's avatar
Bruce Momjian committed
376
	text	   *indexdef;
377 378
	HeapTuple	ht_idx;
	HeapTuple	ht_idxrel;
379
	HeapTuple	ht_am;
Bruce Momjian's avatar
Bruce Momjian committed
380 381
	Form_pg_index idxrec;
	Form_pg_class idxrelrec;
382
	Form_pg_am	amrec;
383
	Oid			indrelid;
Bruce Momjian's avatar
Bruce Momjian committed
384 385
	int			len;
	int			keyno;
386
	Oid			keycoltypes[INDEX_MAX_KEYS];
387 388
	StringInfoData buf;
	StringInfoData keybuf;
Bruce Momjian's avatar
Bruce Momjian committed
389
	char	   *sep;
390

391
	/*
392 393
	 * Fetch the pg_index tuple by the Oid of the index
	 */
394 395 396
	ht_idx = SearchSysCache(INDEXRELID,
							ObjectIdGetDatum(indexrelid),
							0, 0, 0);
397
	if (!HeapTupleIsValid(ht_idx))
398
		elog(ERROR, "syscache lookup for index %u failed", indexrelid);
Bruce Momjian's avatar
Bruce Momjian committed
399
	idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
400

401 402 403
	indrelid = idxrec->indrelid;
	Assert(indexrelid == idxrec->indexrelid);

404
	/*
405 406
	 * Fetch the pg_class tuple of the index relation
	 */
407
	ht_idxrel = SearchSysCache(RELOID,
408
							   ObjectIdGetDatum(indexrelid),
409
							   0, 0, 0);
410
	if (!HeapTupleIsValid(ht_idxrel))
411
		elog(ERROR, "syscache lookup for relid %u failed", indexrelid);
Bruce Momjian's avatar
Bruce Momjian committed
412
	idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
413

414
	/*
415
	 * Fetch the pg_am tuple of the index' access method
416
	 */
417 418 419 420 421 422
	ht_am = SearchSysCache(AMOID,
						   ObjectIdGetDatum(idxrelrec->relam),
						   0, 0, 0);
	if (!HeapTupleIsValid(ht_am))
		elog(ERROR, "syscache lookup for AM %u failed", idxrelrec->relam);
	amrec = (Form_pg_am) GETSTRUCT(ht_am);
423

424
	/*
425 426
	 * Start the index definition.  Note that the index's name should never
	 * be schema-qualified, but the indexed rel's name may be.
427
	 */
428
	initStringInfo(&buf);
429
	appendStringInfo(&buf, "CREATE %sINDEX %s ON %s USING %s (",
430
					 idxrec->indisunique ? "UNIQUE " : "",
431
					 quote_identifier(NameStr(idxrelrec->relname)),
432
					 generate_relation_name(indrelid),
433
					 quote_identifier(NameStr(amrec->amname)));
Bruce Momjian's avatar
Bruce Momjian committed
434

435
	/*
436
	 * Collect the indexed attributes in keybuf
437
	 */
438
	initStringInfo(&keybuf);
439 440 441
	sep = "";
	for (keyno = 0; keyno < INDEX_MAX_KEYS; keyno++)
	{
442
		AttrNumber	attnum = idxrec->indkey[keyno];
443
		char	   *attname;
444 445

		if (attnum == InvalidAttrNumber)
446 447
			break;

448 449 450
		attname = get_relid_attribute_name(indrelid, attnum);
		keycoltypes[keyno] = get_atttype(indrelid, attnum);

451
		appendStringInfo(&keybuf, sep);
452 453
		sep = ", ";

454
		/*
455 456
		 * Add the indexed field name
		 */
457
		appendStringInfo(&keybuf, "%s", quote_identifier(attname));
458

459
		/*
460 461 462
		 * If not a functional index, add the operator class name
		 */
		if (idxrec->indproc == InvalidOid)
463
			get_opclass_name(idxrec->indclass[keyno],
464
							 keycoltypes[keyno],
465
							 &keybuf);
466 467 468 469
	}

	if (idxrec->indproc != InvalidOid)
	{
470 471 472 473
		/*
		 * For functional index say 'func (attrs) opclass'
		 */
		appendStringInfo(&buf, "%s(%s)",
474 475
						 generate_function_name(idxrec->indproc,
												keyno, keycoltypes),
476
						 keybuf.data);
477 478 479
		get_opclass_name(idxrec->indclass[0],
						 get_func_rettype(idxrec->indproc),
						 &buf);
480 481
	}
	else
482
	{
483
		/*
484
		 * Otherwise say 'attr opclass [, ...]'
Bruce Momjian's avatar
Bruce Momjian committed
485
		 */
486
		appendStringInfo(&buf, "%s", keybuf.data);
487 488
	}

489
	appendStringInfoChar(&buf, ')');
490

491
	/*
492
	 * If it's a partial index, decompile and append the predicate
493
	 */
494 495
	if (VARSIZE(&idxrec->indpred) > VARHDRSZ)
	{
496 497 498 499
		Node	   *node;
		List	   *context;
		char	   *exprstr;
		char	   *str;
500 501 502

		/* Convert TEXT object to C string */
		exprstr = DatumGetCString(DirectFunctionCall1(textout,
503
									 PointerGetDatum(&idxrec->indpred)));
504 505
		/* Convert expression to node tree */
		node = (Node *) stringToNode(exprstr);
506

507 508 509 510 511 512 513 514
		/*
		 * If top level is a List, assume it is an implicit-AND structure,
		 * and convert to explicit AND.  This is needed for partial index
		 * predicates.
		 */
		if (node && IsA(node, List))
			node = (Node *) make_ands_explicit((List *) node);
		/* Deparse */
515
		context = deparse_context_for(get_rel_name(indrelid), indrelid);
516 517 518
		str = deparse_expression(node, context, false);
		appendStringInfo(&buf, " WHERE %s", str);
	}
519

520
	/*
521
	 * Create the result as a TEXT datum, and free working data
522
	 */
523
	len = buf.len + VARHDRSZ;
524
	indexdef = (text *) palloc(len);
Jan Wieck's avatar
TOAST  
Jan Wieck committed
525
	VARATT_SIZEP(indexdef) = len;
526
	memcpy(VARDATA(indexdef), buf.data, buf.len);
527

528 529
	pfree(buf.data);
	pfree(keybuf.data);
530

531 532
	ReleaseSysCache(ht_idx);
	ReleaseSysCache(ht_idxrel);
533
	ReleaseSysCache(ht_am);
534

535
	PG_RETURN_TEXT_P(indexdef);
536 537 538
}


539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
/*
 * pg_get_constraintdef
 *
 * Returns the definition for the constraint, ie, everything that needs to
 * appear after "ALTER TABLE ... ADD CONSTRAINT <constraintname>".
 *
 * XXX The present implementation only works for foreign-key constraints, but
 * it could and should handle anything pg_constraint stores.
 */
Datum
pg_get_constraintdef(PG_FUNCTION_ARGS)
{
	Oid				constraintId = PG_GETARG_OID(0);
	text		   *result;
	StringInfoData	buf;
	int				len;
	Relation		conDesc;
	SysScanDesc		conscan;
	ScanKeyData		skey[1];
	HeapTuple		tup;
	Form_pg_constraint	conForm;

	/*
	 * Fetch the pg_constraint row.  There's no syscache for pg_constraint
	 * so we must do it the hard way.
	 */
	conDesc = heap_openr(ConstraintRelationName, AccessShareLock);

	ScanKeyEntryInitialize(&skey[0], 0x0,
						   ObjectIdAttributeNumber, F_OIDEQ,
						   ObjectIdGetDatum(constraintId));

	conscan = systable_beginscan(conDesc, ConstraintOidIndex, true,
								 SnapshotNow, 1, skey);

	tup = systable_getnext(conscan);
	if (!HeapTupleIsValid(tup))
		elog(ERROR, "Failed to find constraint with OID %u", constraintId);
	conForm = (Form_pg_constraint) GETSTRUCT(tup);

	initStringInfo(&buf);

	switch (conForm->contype)
	{
		case CONSTRAINT_FOREIGN:
		{
			Datum			val;
			bool			isnull;
			const char	   *string;

			/* Start off the constraint definition */
			appendStringInfo(&buf, "FOREIGN KEY (");

			/* Fetch and build referencing-column list */
			val = heap_getattr(tup, Anum_pg_constraint_conkey,
							   RelationGetDescr(conDesc), &isnull);
			if (isnull)
				elog(ERROR, "pg_get_constraintdef: Null conkey for constraint %u",
					 constraintId);

			decompile_column_index_array(val, conForm->conrelid, &buf);

			/* add foreign relation name */
			appendStringInfo(&buf, ") REFERENCES %s(",
							 generate_relation_name(conForm->confrelid));

			/* Fetch and build referenced-column list */
			val = heap_getattr(tup, Anum_pg_constraint_confkey,
							   RelationGetDescr(conDesc), &isnull);
			if (isnull)
				elog(ERROR, "pg_get_constraintdef: Null confkey for constraint %u",
					 constraintId);

			decompile_column_index_array(val, conForm->confrelid, &buf);

			appendStringInfo(&buf, ")");

			/* Add match type */
			switch (conForm->confmatchtype)
			{
				case FKCONSTR_MATCH_FULL:
					string = " MATCH FULL";
					break;
				case FKCONSTR_MATCH_PARTIAL:
					string = " MATCH PARTIAL";
					break;
				case FKCONSTR_MATCH_UNSPECIFIED:
					string = "";
					break;
				default:
					elog(ERROR, "pg_get_constraintdef: Unknown confmatchtype '%c' for constraint %u",
						 conForm->confmatchtype, constraintId);
					string = ""; /* keep compiler quiet */
					break;
			}
			appendStringInfo(&buf, "%s", string);

			/* Add ON UPDATE and ON DELETE clauses */
			switch (conForm->confupdtype)
			{
				case FKCONSTR_ACTION_NOACTION:
					string = "NO ACTION";
					break;
				case FKCONSTR_ACTION_RESTRICT:
					string = "RESTRICT";
					break;
				case FKCONSTR_ACTION_CASCADE:
					string = "CASCADE";
					break;
				case FKCONSTR_ACTION_SETNULL:
					string = "SET NULL";
					break;
				case FKCONSTR_ACTION_SETDEFAULT:
					string = "SET DEFAULT";
					break;
				default:
					elog(ERROR, "pg_get_constraintdef: Unknown confupdtype '%c' for constraint %u",
						 conForm->confupdtype, constraintId);
					string = ""; /* keep compiler quiet */
					break;
			}
			appendStringInfo(&buf, " ON UPDATE %s", string);

			switch (conForm->confdeltype)
			{
				case FKCONSTR_ACTION_NOACTION:
					string = "NO ACTION";
					break;
				case FKCONSTR_ACTION_RESTRICT:
					string = "RESTRICT";
					break;
				case FKCONSTR_ACTION_CASCADE:
					string = "CASCADE";
					break;
				case FKCONSTR_ACTION_SETNULL:
					string = "SET NULL";
					break;
				case FKCONSTR_ACTION_SETDEFAULT:
					string = "SET DEFAULT";
					break;
				default:
					elog(ERROR, "pg_get_constraintdef: Unknown confdeltype '%c' for constraint %u",
						 conForm->confdeltype, constraintId);
					string = ""; /* keep compiler quiet */
					break;
			}
			appendStringInfo(&buf, " ON DELETE %s", string);

			break;
		}

			/*
			 * XXX Add more code here for other contypes
			 */
		default:
			elog(ERROR, "pg_get_constraintdef: unsupported constraint type '%c'",
				 conForm->contype);
			break;
	}

	/* Record the results */
	len = buf.len + VARHDRSZ;
	result = (text *) palloc(len);
	VARATT_SIZEP(result) = len;
	memcpy(VARDATA(result), buf.data, buf.len);

	/* Cleanup */
	pfree(buf.data);
	systable_endscan(conscan);
	heap_close(conDesc, AccessShareLock);

	PG_RETURN_TEXT_P(result);
}


/*
 * Convert an int16[] Datum into a comma-separated list of column names
 * for the indicated relation; append the list to buf.
 */
static void
decompile_column_index_array(Datum column_index_array, Oid relId,
							 StringInfo buf)
{
	Datum	   *keys;
	int			nKeys;
	int			j;

	/* Extract data from array of int16 */
	deconstruct_array(DatumGetArrayTypeP(column_index_array),
					  true, 2, 's',
					  &keys, &nKeys);

	for (j = 0; j < nKeys; j++)
	{
		char	   *colName;

		colName	= get_attname(relId, DatumGetInt16(keys[j]));

		if (j == 0)
			appendStringInfo(buf, "%s",
							 quote_identifier(colName));
		else
			appendStringInfo(buf, ", %s",
							 quote_identifier(colName));
	}
}


747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
/* ----------
 * get_expr			- Decompile an expression tree
 *
 * Input: an expression tree in nodeToString form, and a relation OID
 *
 * Output: reverse-listed expression
 *
 * Currently, the expression can only refer to a single relation, namely
 * the one specified by the second parameter.  This is sufficient for
 * partial indexes, column default expressions, etc.
 * ----------
 */
Datum
pg_get_expr(PG_FUNCTION_ARGS)
{
762 763 764 765 766 767 768 769
	text	   *expr = PG_GETARG_TEXT_P(0);
	Oid			relid = PG_GETARG_OID(1);
	text	   *result;
	Node	   *node;
	List	   *context;
	char	   *exprstr;
	char	   *relname;
	char	   *str;
770 771 772 773 774 775 776 777 778 779 780 781 782 783

	/* Get the name for the relation */
	relname = get_rel_name(relid);
	if (relname == NULL)
		PG_RETURN_NULL();		/* should we raise an error? */

	/* Convert input TEXT object to C string */
	exprstr = DatumGetCString(DirectFunctionCall1(textout,
												  PointerGetDatum(expr)));

	/* Convert expression to node tree */
	node = (Node *) stringToNode(exprstr);

	/*
784 785
	 * If top level is a List, assume it is an implicit-AND structure, and
	 * convert to explicit AND.  This is needed for partial index
786 787 788 789 790 791 792 793
	 * predicates.
	 */
	if (node && IsA(node, List))
		node = (Node *) make_ands_explicit((List *) node);

	/* Deparse */
	context = deparse_context_for(relname, relid);
	str = deparse_expression(node, context, false);
794

795 796 797 798 799 800 801 802
	/* Pass the result back as TEXT */
	result = DatumGetTextP(DirectFunctionCall1(textin,
											   CStringGetDatum(str)));

	PG_RETURN_TEXT_P(result);
}


803 804 805 806 807
/* ----------
 * get_userbyid			- Get a user name by usesysid and
 *				  fallback to 'unknown (UID=n)'
 * ----------
 */
808 809
Datum
pg_get_userbyid(PG_FUNCTION_ARGS)
810
{
811 812
	int32		uid = PG_GETARG_INT32(0);
	Name		result;
813
	HeapTuple	usertup;
Bruce Momjian's avatar
Bruce Momjian committed
814
	Form_pg_shadow user_rec;
815

816
	/*
817 818
	 * Allocate space for the result
	 */
819
	result = (Name) palloc(NAMEDATALEN);
820
	memset(NameStr(*result), 0, NAMEDATALEN);
821

822
	/*
823 824
	 * Get the pg_shadow entry and print the result
	 */
825 826 827
	usertup = SearchSysCache(SHADOWSYSID,
							 ObjectIdGetDatum(uid),
							 0, 0, 0);
828 829
	if (HeapTupleIsValid(usertup))
	{
Bruce Momjian's avatar
Bruce Momjian committed
830
		user_rec = (Form_pg_shadow) GETSTRUCT(usertup);
831
		StrNCpy(NameStr(*result), NameStr(user_rec->usename), NAMEDATALEN);
832
		ReleaseSysCache(usertup);
833 834
	}
	else
835
		sprintf(NameStr(*result), "unknown (UID=%d)", uid);
836

837
	PG_RETURN_NAME(result);
838 839
}

840 841 842 843 844 845
/* ----------
 * deparse_expression			- General utility for deparsing expressions
 *
 * expr is the node tree to be deparsed.  It must be a transformed expression
 * tree (ie, not the raw output of gram.y).
 *
846 847
 * dpcontext is a list of deparse_namespace nodes representing the context
 * for interpreting Vars in the node tree.
848 849 850 851 852 853 854
 *
 * forceprefix is TRUE to force all Vars to be prefixed with their table names.
 *
 * The result is a palloc'd string.
 * ----------
 */
char *
855
deparse_expression(Node *expr, List *dpcontext, bool forceprefix)
856
{
857 858
	StringInfoData buf;
	deparse_context context;
859 860 861

	initStringInfo(&buf);
	context.buf = &buf;
862 863
	context.namespaces = dpcontext;
	context.varprefix = forceprefix;
864 865 866 867 868

	get_rule_expr(expr, &context);

	return buf.data;
}
869

870 871 872
/* ----------
 * deparse_context_for			- Build deparse context for a single relation
 *
873 874 875
 * Given the reference name (alias) and OID of a relation, build deparsing
 * context for an expression referencing only that relation (as varno 1,
 * varlevelsup 0).  This is sufficient for many uses of deparse_expression.
876 877 878
 * ----------
 */
List *
879
deparse_context_for(const char *aliasname, Oid relid)
880 881 882 883 884 885 886 887
{
	deparse_namespace *dpns;
	RangeTblEntry *rte;

	dpns = (deparse_namespace *) palloc(sizeof(deparse_namespace));

	/* Build a minimal RTE for the rel */
	rte = makeNode(RangeTblEntry);
888
	rte->rtekind = RTE_RELATION;
889
	rte->relid = relid;
890
	rte->eref = makeAlias(aliasname, NIL);
891 892
	rte->inh = false;
	rte->inFromCl = true;
893

894 895
	/* Build one-element rtable */
	dpns->rtable = makeList1(rte);
896 897
	dpns->outer_varno = dpns->inner_varno = 0;
	dpns->outer_rte = dpns->inner_rte = NULL;
898

899 900 901 902 903 904 905 906 907
	/* Return a one-deep namespace stack */
	return makeList1(dpns);
}

/*
 * deparse_context_for_plan		- Build deparse context for a plan node
 *
 * We assume we are dealing with an upper-level plan node having either
 * one or two referenceable children (pass innercontext = NULL if only one).
908 909 910
 * The passed-in Nodes should be made using deparse_context_for_subplan
 * and/or deparse_context_for_relation.  The resulting context will work
 * for deparsing quals, tlists, etc of the plan node.
911 912 913 914
 *
 * An rtable list can also be passed in case plain Vars might be seen.
 * This is not needed for true upper-level expressions, but is helpful for
 * Sort nodes and similar cases with slightly bogus targetlists.
915 916 917
 */
List *
deparse_context_for_plan(int outer_varno, Node *outercontext,
918 919
						 int inner_varno, Node *innercontext,
						 List *rtable)
920 921 922 923 924
{
	deparse_namespace *dpns;

	dpns = (deparse_namespace *) palloc(sizeof(deparse_namespace));

925
	dpns->rtable = rtable;
926 927 928 929
	dpns->outer_varno = outer_varno;
	dpns->outer_rte = (RangeTblEntry *) outercontext;
	dpns->inner_varno = inner_varno;
	dpns->inner_rte = (RangeTblEntry *) innercontext;
930 931 932 933 934

	/* Return a one-deep namespace stack */
	return makeList1(dpns);
}

935
/*
936
 * deparse_context_for_rte		- Build deparse context for 1 relation
937 938 939
 *
 * Helper routine to build one of the inputs for deparse_context_for_plan.
 *
940 941
 * The returned node is actually the given RangeTblEntry, but we declare it
 * as just Node to discourage callers from assuming anything.
942 943
 */
Node *
944
deparse_context_for_rte(RangeTblEntry *rte)
945 946 947 948
{
	return (Node *) rte;
}

949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
/*
 * deparse_context_for_subplan	- Build deparse context for a plan node
 *
 * Helper routine to build one of the inputs for deparse_context_for_plan.
 * Pass the tlist of the subplan node, plus the query rangetable.
 *
 * The returned node is actually a RangeTblEntry, but we declare it as just
 * Node to discourage callers from assuming anything.
 */
Node *
deparse_context_for_subplan(const char *name, List *tlist,
							List *rtable)
{
	RangeTblEntry *rte = makeNode(RangeTblEntry);
	List	   *attrs = NIL;
	int			nattrs = 0;
	int			rtablelength = length(rtable);
	List	   *tl;
	char		buf[32];

	foreach(tl, tlist)
	{
		TargetEntry *tle = lfirst(tl);
		Resdom *resdom = tle->resdom;

		nattrs++;
		Assert(resdom->resno == nattrs);
		if (resdom->resname)
		{
			attrs = lappend(attrs, makeString(resdom->resname));
			continue;
		}
		if (tle->expr && IsA(tle->expr, Var))
		{
			Var	   *var = (Var *) tle->expr;

			/* varno/varattno won't be any good, but varnoold might be */
			if (var->varnoold > 0 && var->varnoold <= rtablelength)
			{
				RangeTblEntry *varrte = rt_fetch(var->varnoold, rtable);
				char *varname;

				varname = get_rte_attribute_name(varrte, var->varoattno);
				attrs = lappend(attrs, makeString(varname));
				continue;
			}
		}
		/* Fallback if can't get name */
		snprintf(buf, sizeof(buf), "?column%d?", resdom->resno);
		attrs = lappend(attrs, makeString(pstrdup(buf)));
	}

	rte->rtekind = RTE_SPECIAL;	/* XXX */
	rte->relid = InvalidOid;
1003
	rte->eref = makeAlias(name, attrs);
1004 1005 1006 1007 1008 1009
	rte->inh = false;
	rte->inFromCl = true;

	return (Node *) rte;
}

1010 1011 1012 1013 1014
/* ----------
 * make_ruledef			- reconstruct the CREATE RULE command
 *				  for a given pg_rewrite tuple
 * ----------
 */
1015 1016
static void
make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc)
1017
{
1018
	char	   *rulename;
1019 1020 1021 1022 1023 1024 1025 1026
	char		ev_type;
	Oid			ev_class;
	int2		ev_attr;
	bool		is_instead;
	char	   *ev_qual;
	char	   *ev_action;
	List	   *actions = NIL;
	int			fno;
1027
	Datum		dat;
1028 1029
	bool		isnull;

1030
	/*
1031 1032
	 * Get the attribute values from the rules tuple
	 */
1033 1034 1035 1036 1037
	fno = SPI_fnumber(rulettc, "rulename");
	dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
	Assert(!isnull);
	rulename = NameStr(*(DatumGetName(dat)));

1038
	fno = SPI_fnumber(rulettc, "ev_type");
1039 1040 1041
	dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
	Assert(!isnull);
	ev_type = DatumGetChar(dat);
1042 1043

	fno = SPI_fnumber(rulettc, "ev_class");
1044 1045 1046
	dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
	Assert(!isnull);
	ev_class = DatumGetObjectId(dat);
1047 1048

	fno = SPI_fnumber(rulettc, "ev_attr");
1049 1050 1051
	dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
	Assert(!isnull);
	ev_attr = DatumGetInt16(dat);
1052 1053

	fno = SPI_fnumber(rulettc, "is_instead");
1054 1055 1056
	dat = SPI_getbinval(ruletup, rulettc, fno, &isnull);
	Assert(!isnull);
	is_instead = DatumGetBool(dat);
1057

1058
	/* these could be nulls */
1059 1060 1061 1062 1063 1064 1065 1066
	fno = SPI_fnumber(rulettc, "ev_qual");
	ev_qual = SPI_getvalue(ruletup, rulettc, fno);

	fno = SPI_fnumber(rulettc, "ev_action");
	ev_action = SPI_getvalue(ruletup, rulettc, fno);
	if (ev_action != NULL)
		actions = (List *) stringToNode(ev_action);

1067
	/*
1068 1069
	 * Build the rules definition text
	 */
1070 1071
	appendStringInfo(buf, "CREATE RULE %s AS ON ",
					 quote_identifier(rulename));
1072 1073 1074 1075 1076

	/* The event the rule is fired for */
	switch (ev_type)
	{
		case '1':
1077
			appendStringInfo(buf, "SELECT");
1078 1079
			break;

1080
		case '2':
1081
			appendStringInfo(buf, "UPDATE");
1082 1083
			break;

1084
		case '3':
1085
			appendStringInfo(buf, "INSERT");
1086 1087
			break;

1088
		case '4':
1089
			appendStringInfo(buf, "DELETE");
1090 1091
			break;

1092 1093 1094 1095 1096
		default:
			elog(ERROR, "get_ruledef: rule %s has unsupported event type %d",
				 rulename, ev_type);
			break;
	}
1097

1098
	/* The relation the rule is fired on */
1099
	appendStringInfo(buf, " TO %s", generate_relation_name(ev_class));
1100
	if (ev_attr > 0)
1101
		appendStringInfo(buf, ".%s",
1102 1103
					  quote_identifier(get_relid_attribute_name(ev_class,
															  ev_attr)));
1104

1105 1106 1107
	/* If the rule has an event qualification, add it */
	if (ev_qual == NULL)
		ev_qual = "";
1108
	if (strlen(ev_qual) > 0 && strcmp(ev_qual, "<>") != 0)
1109 1110 1111
	{
		Node	   *qual;
		Query	   *query;
1112
		deparse_context context;
1113
		deparse_namespace dpns;
1114 1115

		appendStringInfo(buf, " WHERE ");
1116

1117
		qual = stringToNode(ev_qual);
1118 1119 1120 1121 1122 1123

		/*
		 * We need to make a context for recognizing any Vars in the qual
		 * (which can only be references to OLD and NEW).  Use the rtable
		 * of the first query in the action list for this purpose.
		 */
1124
		query = (Query *) lfirst(actions);
1125

1126 1127 1128 1129 1130 1131 1132
		/*
		 * If the action is INSERT...SELECT, OLD/NEW have been pushed
		 * down into the SELECT, and that's what we need to look at.
		 * (Ugly kluge ... try to fix this when we redesign querytrees.)
		 */
		query = getInsertSelectQuery(query, NULL);

1133
		context.buf = buf;
1134
		context.namespaces = makeList1(&dpns);
1135
		context.varprefix = (length(query->rtable) != 1);
1136
		dpns.rtable = query->rtable;
1137 1138
		dpns.outer_varno = dpns.inner_varno = 0;
		dpns.outer_rte = dpns.inner_rte = NULL;
1139 1140

		get_rule_expr(qual, &context);
1141
	}
1142

1143
	appendStringInfo(buf, " DO ");
1144

1145 1146
	/* The INSTEAD keyword (if so) */
	if (is_instead)
1147
		appendStringInfo(buf, "INSTEAD ");
1148

1149 1150 1151 1152 1153
	/* Finally the rules actions */
	if (length(actions) > 1)
	{
		List	   *action;
		Query	   *query;
1154

1155
		appendStringInfo(buf, "(");
1156 1157 1158
		foreach(action, actions)
		{
			query = (Query *) lfirst(action);
1159
			get_query_def(query, buf, NIL, NULL);
1160
			appendStringInfo(buf, "; ");
1161
		}
1162
		appendStringInfo(buf, ");");
1163
	}
1164 1165 1166 1167
	else if (length(actions) == 0)
	{
		appendStringInfo(buf, "NOTHING;");
	}
1168 1169
	else
	{
1170
		Query	   *query;
1171

1172 1173 1174
		query = (Query *) lfirst(actions);
		get_query_def(query, buf, NIL, NULL);
		appendStringInfo(buf, ";");
1175 1176 1177 1178 1179 1180 1181 1182 1183
	}
}


/* ----------
 * make_viewdef			- reconstruct the SELECT part of a
 *				  view rewrite rule
 * ----------
 */
1184 1185
static void
make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc)
1186
{
1187 1188 1189 1190 1191 1192 1193 1194
	Query	   *query;
	char		ev_type;
	Oid			ev_class;
	int2		ev_attr;
	bool		is_instead;
	char	   *ev_qual;
	char	   *ev_action;
	List	   *actions = NIL;
1195
	Relation	ev_relation;
1196 1197 1198
	int			fno;
	bool		isnull;

1199
	/*
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
	 * Get the attribute values from the rules tuple
	 */
	fno = SPI_fnumber(rulettc, "ev_type");
	ev_type = (char) SPI_getbinval(ruletup, rulettc, fno, &isnull);

	fno = SPI_fnumber(rulettc, "ev_class");
	ev_class = (Oid) SPI_getbinval(ruletup, rulettc, fno, &isnull);

	fno = SPI_fnumber(rulettc, "ev_attr");
	ev_attr = (int2) SPI_getbinval(ruletup, rulettc, fno, &isnull);

	fno = SPI_fnumber(rulettc, "is_instead");
	is_instead = (bool) SPI_getbinval(ruletup, rulettc, fno, &isnull);

	fno = SPI_fnumber(rulettc, "ev_qual");
	ev_qual = SPI_getvalue(ruletup, rulettc, fno);

	fno = SPI_fnumber(rulettc, "ev_action");
	ev_action = SPI_getvalue(ruletup, rulettc, fno);
	if (ev_action != NULL)
		actions = (List *) stringToNode(ev_action);

	if (length(actions) != 1)
1223 1224 1225 1226
	{
		appendStringInfo(buf, "Not a view");
		return;
	}
1227 1228 1229

	query = (Query *) lfirst(actions);

1230
	if (ev_type != '1' || ev_attr >= 0 || !is_instead ||
1231
		strcmp(ev_qual, "<>") != 0 || query->commandType != CMD_SELECT)
1232 1233 1234 1235
	{
		appendStringInfo(buf, "Not a view");
		return;
	}
1236

1237 1238 1239
	ev_relation = heap_open(ev_class, AccessShareLock);

	get_query_def(query, buf, NIL, RelationGetDescr(ev_relation));
1240
	appendStringInfo(buf, ";");
1241 1242

	heap_close(ev_relation, AccessShareLock);
1243 1244 1245 1246
}


/* ----------
1247 1248 1249 1250
 * get_query_def			- Parse back one query parsetree
 *
 * If resultDesc is not NULL, then it is the output tuple descriptor for
 * the view represented by a SELECT query.
1251 1252
 * ----------
 */
1253
static void
1254 1255
get_query_def(Query *query, StringInfo buf, List *parentnamespace,
			  TupleDesc resultDesc)
1256
{
1257
	deparse_context context;
1258
	deparse_namespace dpns;
1259

1260
	context.buf = buf;
1261 1262
	context.namespaces = lcons(&dpns, parentnamespace);
	context.varprefix = (parentnamespace != NIL ||
1263
						 length(query->rtable) != 1);
1264
	dpns.rtable = query->rtable;
1265 1266
	dpns.outer_varno = dpns.inner_varno = 0;
	dpns.outer_rte = dpns.inner_rte = NULL;
1267

1268 1269
	switch (query->commandType)
	{
Bruce Momjian's avatar
Bruce Momjian committed
1270
		case CMD_SELECT:
1271
			get_select_query_def(query, &context, resultDesc);
1272 1273 1274
			break;

		case CMD_UPDATE:
1275
			get_update_query_def(query, &context);
1276 1277 1278
			break;

		case CMD_INSERT:
1279
			get_insert_query_def(query, &context);
1280 1281 1282
			break;

		case CMD_DELETE:
1283
			get_delete_query_def(query, &context);
1284 1285 1286
			break;

		case CMD_NOTHING:
1287
			appendStringInfo(buf, "NOTHING");
1288 1289
			break;

1290 1291 1292 1293
		case CMD_UTILITY:
			get_utility_query_def(query, &context);
			break;

1294
		default:
1295 1296
			elog(ERROR, "get_query_def: unknown query command type %d",
				 query->commandType);
1297 1298
			break;
	}
1299 1300 1301 1302 1303 1304 1305
}


/* ----------
 * get_select_query_def			- Parse back a SELECT parsetree
 * ----------
 */
1306
static void
1307 1308
get_select_query_def(Query *query, deparse_context *context,
					 TupleDesc resultDesc)
1309 1310
{
	StringInfo	buf = context->buf;
1311
	bool		force_colno;
1312 1313 1314
	char	   *sep;
	List	   *l;

1315 1316 1317 1318
	/*
	 * If the Query node has a setOperations tree, then it's the top level
	 * of a UNION/INTERSECT/EXCEPT query; only the ORDER BY and LIMIT
	 * fields are interesting in the top query itself.
1319 1320 1321
	 */
	if (query->setOperations)
	{
1322
		get_setop_query(query->setOperations, query, context, resultDesc);
1323
		/* ORDER BY clauses must be simple in this case */
1324
		force_colno = true;
1325 1326 1327
	}
	else
	{
1328
		get_basic_select_query(query, context, resultDesc);
1329
		force_colno = false;
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
	}

	/* Add the ORDER BY clause if given */
	if (query->sortClause != NIL)
	{
		appendStringInfo(buf, " ORDER BY ");
		sep = "";
		foreach(l, query->sortClause)
		{
			SortClause *srt = (SortClause *) lfirst(l);
1340 1341
			Node	   *sortexpr;
			Oid			sortcoltype;
1342 1343 1344
			char	   *opname;

			appendStringInfo(buf, sep);
1345 1346 1347 1348 1349
			sortexpr = get_rule_sortgroupclause(srt, query->targetList,
												force_colno, context);
			sortcoltype = exprType(sortexpr);
			opname = generate_operator_name(srt->sortop,
											sortcoltype, sortcoltype);
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
			if (strcmp(opname, "<") != 0)
			{
				if (strcmp(opname, ">") == 0)
					appendStringInfo(buf, " DESC");
				else
					appendStringInfo(buf, " USING %s", opname);
			}
			sep = ", ";
		}
	}
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369

	/* Add the LIMIT clause if given */
	if (query->limitOffset != NULL)
	{
		appendStringInfo(buf, " OFFSET ");
		get_rule_expr(query->limitOffset, context);
	}
	if (query->limitCount != NULL)
	{
		appendStringInfo(buf, " LIMIT ");
1370 1371 1372 1373 1374
		if (IsA(query->limitCount, Const) &&
			((Const *) query->limitCount)->constisnull)
			appendStringInfo(buf, "ALL");
		else
			get_rule_expr(query->limitCount, context);
1375
	}
1376 1377 1378
}

static void
1379 1380
get_basic_select_query(Query *query, deparse_context *context,
					   TupleDesc resultDesc)
1381
{
1382
	StringInfo	buf = context->buf;
1383 1384
	char	   *sep;
	List	   *l;
1385
	int			colno;
1386

1387
	/*
1388 1389
	 * Build up the query string - first we say SELECT
	 */
1390
	appendStringInfo(buf, "SELECT");
1391

1392 1393 1394
	/* Add the DISTINCT clause if given */
	if (query->distinctClause != NIL)
	{
1395
		if (has_distinct_on_clause(query))
1396 1397 1398 1399 1400 1401 1402 1403
		{
			appendStringInfo(buf, " DISTINCT ON (");
			sep = "";
			foreach(l, query->distinctClause)
			{
				SortClause *srt = (SortClause *) lfirst(l);

				appendStringInfo(buf, sep);
1404 1405
				get_rule_sortgroupclause(srt, query->targetList,
										 false, context);
1406 1407 1408 1409
				sep = ", ";
			}
			appendStringInfo(buf, ")");
		}
1410 1411
		else
			appendStringInfo(buf, " DISTINCT");
1412 1413
	}

1414
	/* Then we tell what to select (the targetlist) */
1415
	sep = " ";
1416
	colno = 0;
1417 1418
	foreach(l, query->targetList)
	{
1419
		TargetEntry *tle = (TargetEntry *) lfirst(l);
1420
		bool		tell_as = false;
1421
		char	   *colname;
1422

1423 1424 1425
		if (tle->resdom->resjunk)
			continue;			/* ignore junk entries */

1426
		appendStringInfo(buf, sep);
1427
		sep = ", ";
1428
		colno++;
1429

1430 1431
		/* Do NOT use get_tle_expr here; see its comments! */
		get_rule_expr(tle->expr, context);
1432

1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
		/*
		 * Figure out what the result column should be called.  In the
		 * context of a view, use the view's tuple descriptor (so as to
		 * pick up the effects of any column RENAME that's been done on the
		 * view).  Otherwise, just use what we can find in the TLE.
		 */
		if (resultDesc && colno <= resultDesc->natts)
			colname = NameStr(resultDesc->attrs[colno-1]->attname);
		else
			colname = tle->resdom->resname;

1444
		/* Check if we must say AS ... */
1445
		if (!IsA(tle->expr, Var))
1446
			tell_as = (strcmp(colname, "?column?") != 0);
1447 1448 1449
		else
		{
			Var		   *var = (Var *) (tle->expr);
1450
			char	   *schemaname;
1451
			char	   *refname;
1452 1453
			char	   *attname;

1454
			get_names_for_var(var, context, &schemaname, &refname, &attname);
1455
			tell_as = (attname == NULL ||
1456
					   strcmp(attname, colname) != 0);
1457 1458 1459 1460
		}

		/* and do if so */
		if (tell_as)
1461
			appendStringInfo(buf, " AS %s", quote_identifier(colname));
1462 1463
	}

1464 1465
	/* Add the FROM clause if needed */
	get_from_clause(query, context);
1466 1467

	/* Add the WHERE clause if given */
1468
	if (query->jointree->quals != NULL)
1469
	{
1470
		appendStringInfo(buf, " WHERE ");
1471
		get_rule_expr(query->jointree->quals, context);
1472 1473
	}

1474
	/* Add the GROUP BY clause if given */
1475 1476
	if (query->groupClause != NULL)
	{
1477
		appendStringInfo(buf, " GROUP BY ");
1478 1479 1480
		sep = "";
		foreach(l, query->groupClause)
		{
1481 1482
			GroupClause *grp = (GroupClause *) lfirst(l);

1483
			appendStringInfo(buf, sep);
1484 1485
			get_rule_sortgroupclause(grp, query->targetList,
									 false, context);
1486 1487
			sep = ", ";
		}
1488
	}
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498

	/* Add the HAVING clause if given */
	if (query->havingQual != NULL)
	{
		appendStringInfo(buf, " HAVING ");
		get_rule_expr(query->havingQual, context);
	}
}

static void
1499 1500
get_setop_query(Node *setOp, Query *query, deparse_context *context,
				TupleDesc resultDesc)
1501 1502 1503 1504 1505 1506 1507
{
	StringInfo	buf = context->buf;

	if (IsA(setOp, RangeTblRef))
	{
		RangeTblRef *rtr = (RangeTblRef *) setOp;
		RangeTblEntry *rte = rt_fetch(rtr->rtindex, query->rtable);
1508
		Query	   *subquery = rte->subquery;
1509 1510

		Assert(subquery != NULL);
1511
		get_query_def(subquery, buf, context->namespaces, resultDesc);
1512 1513 1514 1515 1516
	}
	else if (IsA(setOp, SetOperationStmt))
	{
		SetOperationStmt *op = (SetOperationStmt *) setOp;

1517
		appendStringInfo(buf, "((");
1518
		get_setop_query(op->larg, query, context, resultDesc);
1519 1520 1521
		switch (op->op)
		{
			case SETOP_UNION:
1522
				appendStringInfo(buf, ") UNION ");
1523 1524
				break;
			case SETOP_INTERSECT:
1525
				appendStringInfo(buf, ") INTERSECT ");
1526 1527
				break;
			case SETOP_EXCEPT:
1528
				appendStringInfo(buf, ") EXCEPT ");
1529 1530 1531 1532 1533 1534
				break;
			default:
				elog(ERROR, "get_setop_query: unexpected set op %d",
					 (int) op->op);
		}
		if (op->all)
1535 1536 1537
			appendStringInfo(buf, "ALL (");
		else
			appendStringInfo(buf, "(");
1538
		get_setop_query(op->rarg, query, context, resultDesc);
1539
		appendStringInfo(buf, "))");
1540 1541 1542 1543 1544 1545 1546 1547
	}
	else
	{
		elog(ERROR, "get_setop_query: unexpected node %d",
			 (int) nodeTag(setOp));
	}
}

1548 1549
/*
 * Display a sort/group clause.
1550 1551
 *
 * Also returns the expression tree, so caller need not find it again.
1552
 */
1553
static Node *
1554 1555 1556 1557 1558 1559 1560 1561 1562
get_rule_sortgroupclause(SortClause *srt, List *tlist, bool force_colno,
						 deparse_context *context)
{
	StringInfo	buf = context->buf;
	TargetEntry *tle;
	Node	   *expr;

	tle = get_sortgroupclause_tle(srt, tlist);
	expr = tle->expr;
1563

1564 1565
	/*
	 * Use column-number form if requested by caller or if expression is a
1566 1567
	 * constant --- a constant is ambiguous (and will be misinterpreted by
	 * findTargetlistEntry()) if we dump it explicitly.
1568 1569 1570 1571 1572 1573 1574 1575
	 */
	if (force_colno || (expr && IsA(expr, Const)))
	{
		Assert(!tle->resdom->resjunk);
		appendStringInfo(buf, "%d", tle->resdom->resno);
	}
	else
		get_rule_expr(expr, context);
1576 1577

	return expr;
1578
}
1579 1580 1581 1582 1583

/* ----------
 * get_insert_query_def			- Parse back an INSERT parsetree
 * ----------
 */
1584
static void
1585
get_insert_query_def(Query *query, deparse_context *context)
1586
{
1587
	StringInfo	buf = context->buf;
1588
	RangeTblEntry *select_rte = NULL;
1589
	RangeTblEntry *rte;
1590
	char	   *sep;
1591 1592
	List	   *l;

1593
	/*
1594 1595
	 * If it's an INSERT ... SELECT there will be a single subquery RTE
	 * for the SELECT.
1596 1597 1598 1599
	 */
	foreach(l, query->rtable)
	{
		rte = (RangeTblEntry *) lfirst(l);
1600
		if (rte->rtekind != RTE_SUBQUERY)
1601
			continue;
1602 1603 1604
		if (select_rte)
			elog(ERROR, "get_insert_query_def: too many RTEs in INSERT!");
		select_rte = rte;
1605
	}
1606

1607
	/*
1608 1609
	 * Start the query with INSERT INTO relname
	 */
1610
	rte = rt_fetch(query->resultRelation, query->rtable);
1611
	Assert(rte->rtekind == RTE_RELATION);
1612
	appendStringInfo(buf, "INSERT INTO %s",
1613
					 generate_relation_name(rte->relid));
1614

1615
	/* Add the insert-column-names list */
1616 1617 1618
	sep = " (";
	foreach(l, query->targetList)
	{
1619
		TargetEntry *tle = (TargetEntry *) lfirst(l);
1620

1621 1622 1623
		if (tle->resdom->resjunk)
			continue;			/* ignore junk entries */

1624
		appendStringInfo(buf, sep);
1625
		sep = ", ";
1626
		appendStringInfo(buf, "%s", quote_identifier(tle->resdom->resname));
1627
	}
1628
	appendStringInfo(buf, ") ");
1629 1630

	/* Add the VALUES or the SELECT */
1631
	if (select_rte == NULL)
1632
	{
1633
		appendStringInfo(buf, "VALUES (");
1634 1635 1636
		sep = "";
		foreach(l, query->targetList)
		{
1637
			TargetEntry *tle = (TargetEntry *) lfirst(l);
1638

1639 1640 1641
			if (tle->resdom->resjunk)
				continue;		/* ignore junk entries */

1642
			appendStringInfo(buf, sep);
1643
			sep = ", ";
1644
			get_tle_expr(tle, context);
1645
		}
1646
		appendStringInfoChar(buf, ')');
1647 1648
	}
	else
1649
		get_query_def(select_rte->subquery, buf, NIL, NULL);
1650 1651 1652 1653 1654 1655 1656
}


/* ----------
 * get_update_query_def			- Parse back an UPDATE parsetree
 * ----------
 */
1657
static void
1658
get_update_query_def(Query *query, deparse_context *context)
1659
{
1660
	StringInfo	buf = context->buf;
1661 1662 1663 1664
	char	   *sep;
	RangeTblEntry *rte;
	List	   *l;

1665
	/*
1666 1667
	 * Start the query with UPDATE relname SET
	 */
1668
	rte = rt_fetch(query->resultRelation, query->rtable);
1669
	Assert(rte->rtekind == RTE_RELATION);
1670
	appendStringInfo(buf, "UPDATE %s%s SET ",
1671
					 only_marker(rte),
1672
					 generate_relation_name(rte->relid));
1673 1674 1675 1676 1677

	/* Add the comma separated list of 'attname = value' */
	sep = "";
	foreach(l, query->targetList)
	{
1678 1679 1680 1681
		TargetEntry *tle = (TargetEntry *) lfirst(l);

		if (tle->resdom->resjunk)
			continue;			/* ignore junk entries */
1682

1683
		appendStringInfo(buf, sep);
1684
		sep = ", ";
1685

1686
		/*
1687 1688 1689
		 * If the update expression is an array assignment, we mustn't put
		 * out "attname =" here; it will come out of the display of the
		 * ArrayRef node instead.
1690
		 */
1691
		if (!tleIsArrayAssign(tle))
1692 1693
			appendStringInfo(buf, "%s = ",
							 quote_identifier(tle->resdom->resname));
1694
		get_tle_expr(tle, context);
1695 1696
	}

1697 1698 1699
	/* Add the FROM clause if needed */
	get_from_clause(query, context);

1700
	/* Finally add a WHERE clause if given */
1701
	if (query->jointree->quals != NULL)
1702
	{
1703
		appendStringInfo(buf, " WHERE ");
1704
		get_rule_expr(query->jointree->quals, context);
1705
	}
1706 1707 1708 1709 1710 1711 1712
}


/* ----------
 * get_delete_query_def			- Parse back a DELETE parsetree
 * ----------
 */
1713
static void
1714
get_delete_query_def(Query *query, deparse_context *context)
1715
{
1716
	StringInfo	buf = context->buf;
1717 1718
	RangeTblEntry *rte;

1719
	/*
1720 1721
	 * Start the query with DELETE FROM relname
	 */
1722
	rte = rt_fetch(query->resultRelation, query->rtable);
1723
	Assert(rte->rtekind == RTE_RELATION);
1724
	appendStringInfo(buf, "DELETE FROM %s%s",
1725
					 only_marker(rte),
1726
					 generate_relation_name(rte->relid));
1727 1728

	/* Add a WHERE clause if given */
1729
	if (query->jointree->quals != NULL)
1730
	{
1731
		appendStringInfo(buf, " WHERE ");
1732
		get_rule_expr(query->jointree->quals, context);
1733
	}
1734 1735
}

1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748

/* ----------
 * get_utility_query_def			- Parse back a UTILITY parsetree
 * ----------
 */
static void
get_utility_query_def(Query *query, deparse_context *context)
{
	StringInfo	buf = context->buf;

	if (query->utilityStmt && IsA(query->utilityStmt, NotifyStmt))
	{
		NotifyStmt *stmt = (NotifyStmt *) query->utilityStmt;
1749

1750
		appendStringInfo(buf, "NOTIFY %s",
1751 1752
						 quote_qualified_identifier(stmt->relation->schemaname,
													stmt->relation->relname));
1753 1754 1755 1756 1757 1758
	}
	else
		elog(ERROR, "get_utility_query_def: unexpected statement type");
}


1759
/*
1760 1761 1762 1763
 * Get the schemaname, refname and attname for a (possibly nonlocal) Var.
 *
 * schemaname is usually returned as NULL.  It will be non-null only if
 * use of the unqualified refname would find the wrong RTE.
1764
 *
1765 1766 1767
 * refname will be returned as NULL if the Var references an unnamed join.
 * In this case the Var *must* be displayed without any qualification.
 *
1768
 * attname will be returned as NULL if the Var represents a whole tuple
1769 1770 1771
 * of the relation.  (Typically we'd want to display the Var as "foo.*",
 * but it's convenient to return NULL to make it easier for callers to
 * distinguish this case.)
1772
 */
1773 1774
static void
get_names_for_var(Var *var, deparse_context *context,
1775
				  char **schemaname, char **refname, char **attname)
1776
{
1777
	List	   *nslist = context->namespaces;
1778
	int			sup = var->varlevelsup;
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
	deparse_namespace *dpns;
	RangeTblEntry *rte;

	/* Find appropriate nesting depth */
	while (sup-- > 0 && nslist != NIL)
		nslist = lnext(nslist);
	if (nslist == NIL)
		elog(ERROR, "get_names_for_var: bogus varlevelsup %d",
			 var->varlevelsup);
	dpns = (deparse_namespace *) lfirst(nslist);

1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
	/* Find the relevant RTE */
	if (var->varno >= 1 && var->varno <= length(dpns->rtable))
		rte = rt_fetch(var->varno, dpns->rtable);
	else if (var->varno == dpns->outer_varno)
		rte = dpns->outer_rte;
	else if (var->varno == dpns->inner_varno)
		rte = dpns->inner_rte;
	else
		rte = NULL;
	if (rte == NULL)
		elog(ERROR, "get_names_for_var: bogus varno %d",
			 var->varno);

	/* Emit results */
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
	*schemaname = NULL;			/* default assumptions */
	*refname = rte->eref->aliasname;

	/* Exceptions occur only if the RTE is alias-less */
	if (rte->alias == NULL)
	{
		if (rte->rtekind == RTE_RELATION)
		{
			/*
			 * It's possible that use of the bare refname would find another
			 * more-closely-nested RTE, or be ambiguous, in which case
			 * we need to specify the schemaname to avoid these errors.
			 */
			if (find_rte_by_refname(rte->eref->aliasname, context) != rte)
				*schemaname =
					get_namespace_name(get_rel_namespace(rte->relid));
		}
		else if (rte->rtekind == RTE_JOIN)
		{
			/* Unnamed join has neither schemaname nor refname */
			*refname = NULL;
		}
	}
1827

1828 1829 1830 1831
	if (var->varattno == InvalidAttrNumber)
		*attname = NULL;
	else
		*attname = get_rte_attribute_name(rte, var->varattno);
1832 1833
}

1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
/*
 * find_rte_by_refname		- look up an RTE by refname in a deparse context
 *
 * Returns NULL if there is no matching RTE or the refname is ambiguous.
 *
 * NOTE: this code is not really correct since it does not take account of
 * the fact that not all the RTEs in a rangetable may be visible from the
 * point where a Var reference appears.  For the purposes we need, however,
 * the only consequence of a false match is that we might stick a schema
 * qualifier on a Var that doesn't really need it.  So it seems close
 * enough.
 */
static RangeTblEntry *
find_rte_by_refname(const char *refname, deparse_context *context)
{
	RangeTblEntry *result = NULL;
	List	   *nslist;

	foreach(nslist, context->namespaces)
	{
		deparse_namespace *dpns = (deparse_namespace *) lfirst(nslist);
		List	   *rtlist;

		foreach(rtlist, dpns->rtable)
		{
			RangeTblEntry *rte = (RangeTblEntry *) lfirst(rtlist);

			if (strcmp(rte->eref->aliasname, refname) == 0)
			{
				if (result)
					return NULL; /* it's ambiguous */
				result = rte;
			}
		}
		if (dpns->outer_rte &&
			strcmp(dpns->outer_rte->eref->aliasname, refname) == 0)
		{
			if (result)
				return NULL;	/* it's ambiguous */
			result = dpns->outer_rte;
		}
		if (dpns->inner_rte &&
			strcmp(dpns->inner_rte->eref->aliasname, refname) == 0)
		{
			if (result)
				return NULL;	/* it's ambiguous */
			result = dpns->inner_rte;
		}
		if (result)
			break;
	}
	return result;
}


1889 1890 1891 1892
/* ----------
 * get_rule_expr			- Parse back an expression
 * ----------
 */
1893
static void
1894
get_rule_expr(Node *node, deparse_context *context)
1895
{
1896 1897
	StringInfo	buf = context->buf;

1898
	if (node == NULL)
1899
		return;
1900

1901
	/*
1902
	 * Each level of get_rule_expr must emit an indivisible term
1903 1904
	 * (parenthesized if necessary) to ensure result is reparsed into the
	 * same expression tree.
1905
	 *
1906 1907
	 * There might be some work left here to support additional node types.
	 * Can we ever see Param nodes here?
1908 1909 1910
	 */
	switch (nodeTag(node))
	{
1911
		case T_Const:
1912
			get_const_expr((Const *) node, context);
1913
			break;
1914

1915
		case T_Var:
1916
			{
1917
				Var		   *var = (Var *) node;
1918
				char	   *schemaname;
1919 1920
				char	   *refname;
				char	   *attname;
1921

1922 1923
				get_names_for_var(var, context,
								  &schemaname, &refname, &attname);
1924
				if (refname && (context->varprefix || attname == NULL))
1925
				{
1926 1927 1928 1929
					if (schemaname)
						appendStringInfo(buf, "%s.",
										 quote_identifier(schemaname));

1930
					if (strcmp(refname, "*NEW*") == 0)
1931
						appendStringInfo(buf, "new.");
1932
					else if (strcmp(refname, "*OLD*") == 0)
1933
						appendStringInfo(buf, "old.");
1934
					else
1935
						appendStringInfo(buf, "%s.",
1936
										 quote_identifier(refname));
1937
				}
1938 1939
				if (attname)
					appendStringInfo(buf, "%s", quote_identifier(attname));
1940 1941
				else
					appendStringInfo(buf, "*");
1942 1943
			}
			break;
1944

1945 1946 1947
		case T_Expr:
			{
				Expr	   *expr = (Expr *) node;
1948
				List	   *args = expr->args;
1949

1950
				/*
1951 1952 1953 1954 1955
				 * Expr nodes have to be handled a bit detailed
				 */
				switch (expr->opType)
				{
					case OP_EXPR:
1956
						get_oper_expr(expr, context);
1957 1958
						break;

1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
					case DISTINCT_EXPR:
						appendStringInfoChar(buf, '(');
						Assert(length(args) == 2);
						{
							/* binary operator */
							Node   *arg1 = (Node *) lfirst(args);
							Node   *arg2 = (Node *) lsecond(args);

							get_rule_expr(arg1, context);
							appendStringInfo(buf, " IS DISTINCT FROM ");
							get_rule_expr(arg2, context);
						}
						appendStringInfoChar(buf, ')');
						break;

1974
					case FUNC_EXPR:
1975
						get_func_expr(expr, context);
1976 1977
						break;

1978
					case OR_EXPR:
1979
						appendStringInfoChar(buf, '(');
1980
						get_rule_expr((Node *) lfirst(args), context);
1981 1982
						while ((args = lnext(args)) != NIL)
						{
1983
							appendStringInfo(buf, " OR ");
1984
							get_rule_expr((Node *) lfirst(args), context);
1985
						}
1986
						appendStringInfoChar(buf, ')');
1987 1988 1989
						break;

					case AND_EXPR:
1990
						appendStringInfoChar(buf, '(');
1991
						get_rule_expr((Node *) lfirst(args), context);
1992 1993
						while ((args = lnext(args)) != NIL)
						{
1994
							appendStringInfo(buf, " AND ");
1995
							get_rule_expr((Node *) lfirst(args), context);
1996
						}
1997
						appendStringInfoChar(buf, ')');
1998 1999 2000
						break;

					case NOT_EXPR:
2001
						appendStringInfo(buf, "(NOT ");
2002
						get_rule_expr((Node *) lfirst(args), context);
2003
						appendStringInfoChar(buf, ')');
2004 2005
						break;

2006 2007 2008 2009 2010 2011 2012
					case SUBPLAN_EXPR:
						/*
						 * We cannot see an already-planned subplan in rule
						 * deparsing, only while EXPLAINing a query plan.
						 * For now, just punt.
						 */
						appendStringInfo(buf, "(subplan)");
2013 2014 2015
						break;

					default:
2016 2017
						elog(ERROR, "get_rule_expr: expr opType %d not supported",
							 expr->opType);
2018 2019
				}
			}
2020
			break;
2021

2022
		case T_Aggref:
2023
			get_agg_expr((Aggref *) node, context);
2024
			break;
2025

2026 2027 2028
		case T_ArrayRef:
			{
				ArrayRef   *aref = (ArrayRef *) node;
2029
				bool		savevarprefix = context->varprefix;
2030 2031
				List	   *lowlist;
				List	   *uplist;
2032

2033 2034
				/*
				 * If we are doing UPDATE array[n] = expr, we need to
2035 2036 2037 2038
				 * suppress any prefix on the array name.  Currently, that
				 * is the only context in which we will see a non-null
				 * refassgnexpr --- but someday a smarter test may be
				 * needed.
2039 2040 2041
				 */
				if (aref->refassgnexpr)
					context->varprefix = false;
2042
				get_rule_expr(aref->refexpr, context);
2043
				context->varprefix = savevarprefix;
2044 2045
				lowlist = aref->reflowerindexpr;
				foreach(uplist, aref->refupperindexpr)
2046
				{
2047
					appendStringInfo(buf, "[");
2048
					if (lowlist)
2049
					{
2050
						get_rule_expr((Node *) lfirst(lowlist), context);
2051
						appendStringInfo(buf, ":");
2052
						lowlist = lnext(lowlist);
2053
					}
2054
					get_rule_expr((Node *) lfirst(uplist), context);
2055
					appendStringInfo(buf, "]");
2056
				}
2057 2058 2059 2060 2061
				if (aref->refassgnexpr)
				{
					appendStringInfo(buf, " = ");
					get_rule_expr(aref->refassgnexpr, context);
				}
2062 2063
			}
			break;
2064

2065 2066 2067
		case T_FieldSelect:
			{
				FieldSelect *fselect = (FieldSelect *) node;
2068
				Oid			argType = exprType(fselect->arg);
2069 2070 2071 2072 2073
				HeapTuple	typetup;
				Form_pg_type typeStruct;
				Oid			typrelid;
				char	   *fieldname;

2074
				/* lookup arg type and get the field name */
2075
				typetup = SearchSysCache(TYPEOID,
2076
										 ObjectIdGetDatum(argType),
2077
										 0, 0, 0);
2078 2079
				if (!HeapTupleIsValid(typetup))
					elog(ERROR, "cache lookup of type %u failed",
2080
						 argType);
2081 2082 2083 2084
				typeStruct = (Form_pg_type) GETSTRUCT(typetup);
				typrelid = typeStruct->typrelid;
				if (!OidIsValid(typrelid))
					elog(ERROR, "Argument type %s of FieldSelect is not a tuple type",
2085 2086
						 format_type_be(argType));
				ReleaseSysCache(typetup);
2087 2088
				fieldname = get_relid_attribute_name(typrelid,
													 fselect->fieldnum);
2089 2090 2091
				/*
				 * If the argument is simple enough, we could emit
				 * arg.fieldname, but most cases where FieldSelect is used
2092
				 * are *not* simple.  So, always use parenthesized syntax.
2093
				 */
2094
				appendStringInfoChar(buf, '(');
2095
				get_rule_expr(fselect->arg, context);
2096
				appendStringInfo(buf, ").%s", quote_identifier(fieldname));
2097 2098 2099
			}
			break;

2100 2101 2102 2103 2104 2105
		case T_RelabelType:
			{
				RelabelType *relabel = (RelabelType *) node;

				appendStringInfoChar(buf, '(');
				get_rule_expr(relabel->arg, context);
2106 2107 2108
				appendStringInfo(buf, ")::%s",
							format_type_with_typemod(relabel->resulttype,
													 relabel->resulttypmod));
2109 2110 2111
			}
			break;

2112
		case T_CaseExpr:
2113
			{
2114 2115 2116
				CaseExpr   *caseexpr = (CaseExpr *) node;
				List	   *temp;

2117
				appendStringInfo(buf, "CASE");
2118 2119 2120 2121
				foreach(temp, caseexpr->args)
				{
					CaseWhen   *when = (CaseWhen *) lfirst(temp);

2122
					appendStringInfo(buf, " WHEN ");
2123
					get_rule_expr(when->expr, context);
2124
					appendStringInfo(buf, " THEN ");
2125
					get_rule_expr(when->result, context);
2126
				}
2127
				appendStringInfo(buf, " ELSE ");
2128
				get_rule_expr(caseexpr->defresult, context);
2129
				appendStringInfo(buf, " END");
2130
			}
2131
			break;
2132

2133 2134
		case T_NullTest:
			{
2135
				NullTest   *ntest = (NullTest *) node;
2136

2137
				appendStringInfo(buf, "(");
2138
				get_rule_expr(ntest->arg, context);
2139 2140 2141
				switch (ntest->nulltesttype)
				{
					case IS_NULL:
2142
						appendStringInfo(buf, " IS NULL)");
2143
						break;
2144
					case IS_NOT_NULL:
2145
						appendStringInfo(buf, " IS NOT NULL)");
2146
						break;
2147 2148 2149
					default:
						elog(ERROR, "get_rule_expr: unexpected nulltesttype %d",
							 (int) ntest->nulltesttype);
2150 2151 2152 2153 2154 2155
				}
			}
			break;

		case T_BooleanTest:
			{
2156
				BooleanTest *btest = (BooleanTest *) node;
2157

2158
				appendStringInfo(buf, "(");
2159
				get_rule_expr(btest->arg, context);
2160 2161 2162
				switch (btest->booltesttype)
				{
					case IS_TRUE:
2163
						appendStringInfo(buf, " IS TRUE)");
2164
						break;
2165
					case IS_NOT_TRUE:
2166
						appendStringInfo(buf, " IS NOT TRUE)");
2167
						break;
2168
					case IS_FALSE:
2169
						appendStringInfo(buf, " IS FALSE)");
2170
						break;
2171
					case IS_NOT_FALSE:
2172
						appendStringInfo(buf, " IS NOT FALSE)");
2173
						break;
2174
					case IS_UNKNOWN:
2175
						appendStringInfo(buf, " IS UNKNOWN)");
2176
						break;
2177
					case IS_NOT_UNKNOWN:
2178
						appendStringInfo(buf, " IS NOT UNKNOWN)");
2179
						break;
2180 2181 2182
					default:
						elog(ERROR, "get_rule_expr: unexpected booltesttype %d",
							 (int) btest->booltesttype);
2183 2184 2185 2186
				}
			}
			break;

2187
		case T_SubLink:
2188
			get_sublink_expr(node, context);
2189
			break;
2190

2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
		case T_Param:
			{
				Param	   *param = (Param *) node;

				switch (param->paramkind)
				{
					case PARAM_NAMED:
					case PARAM_NEW:
					case PARAM_OLD:
						appendStringInfo(buf, "$%s", param->paramname);
						break;
					case PARAM_NUM:
					case PARAM_EXEC:
						appendStringInfo(buf, "$%d", param->paramid);
						break;
					default:
						appendStringInfo(buf, "(param)");
						break;
				}
			}
			break;

2213
		default:
2214
			elog(ERROR, "get_rule_expr: unknown node type %d", nodeTag(node));
2215 2216
			break;
	}
2217 2218 2219
}


2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281
/*
 * get_oper_expr			- Parse back an Oper node
 */
static void
get_oper_expr(Expr *expr, deparse_context *context)
{
	StringInfo	buf = context->buf;
	Oid			opno = ((Oper *) expr->oper)->opno;
	List	   *args = expr->args;

	appendStringInfoChar(buf, '(');
	if (length(args) == 2)
	{
		/* binary operator */
		Node   *arg1 = (Node *) lfirst(args);
		Node   *arg2 = (Node *) lsecond(args);

		get_rule_expr(arg1, context);
		appendStringInfo(buf, " %s ",
						 generate_operator_name(opno,
												exprType(arg1),
												exprType(arg2)));
		get_rule_expr(arg2, context);
	}
	else
	{
		/* unary operator --- but which side? */
		Node	   *arg = (Node *) lfirst(args);
		HeapTuple	tp;
		Form_pg_operator optup;

		tp = SearchSysCache(OPEROID,
							ObjectIdGetDatum(opno),
							0, 0, 0);
		if (!HeapTupleIsValid(tp))
			elog(ERROR, "cache lookup for operator %u failed", opno);
		optup = (Form_pg_operator) GETSTRUCT(tp);
		switch (optup->oprkind)
		{
			case 'l':
				appendStringInfo(buf, "%s ",
								 generate_operator_name(opno,
														InvalidOid,
														exprType(arg)));
				get_rule_expr(arg, context);
				break;
			case 'r':
				get_rule_expr(arg, context);
				appendStringInfo(buf, " %s",
								 generate_operator_name(opno,
														exprType(arg),
														InvalidOid));
				break;
			default:
				elog(ERROR, "get_rule_expr: bogus oprkind");
		}
		ReleaseSysCache(tp);
	}
	appendStringInfoChar(buf, ')');
}

/*
2282 2283
 * get_func_expr			- Parse back a Func node
 */
2284
static void
2285
get_func_expr(Expr *expr, deparse_context *context)
2286
{
2287
	StringInfo	buf = context->buf;
2288
	Func	   *func = (Func *) (expr->oper);
2289
	Oid			funcoid = func->funcid;
2290
	int32		coercedTypmod;
2291 2292
	Oid			argtypes[FUNC_MAX_ARGS];
	int			nargs;
2293 2294 2295
	List	   *l;
	char	   *sep;

2296 2297 2298 2299 2300 2301 2302
	/*
	 * Check to see if function is a length-coercion function for some
	 * datatype.  If so, display the operation as a type cast.
	 */
	if (exprIsLengthCoercion((Node *) expr, &coercedTypmod))
	{
		Node	   *arg = lfirst(expr->args);
2303
		Oid			rettype = get_func_rettype(funcoid);
2304
		char	   *typdesc;
2305 2306

		/*
2307 2308
		 * Strip off any type coercions on the input, so we don't print
		 * redundancies like x::bpchar::character(8).
2309 2310
		 *
		 * XXX Are there any cases where this is a bad idea?
2311
		 */
2312
		arg = strip_type_coercion(arg, rettype);
2313

2314 2315
		appendStringInfoChar(buf, '(');
		get_rule_expr(arg, context);
2316

2317
		/*
2318
		 * Show typename with appropriate length decoration. Note that
2319
		 * since exprIsLengthCoercion succeeded, the function's output
2320 2321 2322
		 * type is the right thing to report.  Also note we don't need
		 * to quote the result of format_type_with_typemod: it takes
		 * care of double-quoting any identifier that needs it.
2323
		 */
2324
		typdesc = format_type_with_typemod(rettype, coercedTypmod);
2325 2326
		appendStringInfo(buf, ")::%s", typdesc);
		pfree(typdesc);
2327

2328 2329 2330 2331
		return;
	}

	/*
2332 2333
	 * Normal function: display as proname(args).  First we need to extract
	 * the argument datatypes.
2334
	 */
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
	nargs = 0;
	foreach(l, expr->args)
	{
		Assert(nargs < FUNC_MAX_ARGS);
		argtypes[nargs] = exprType((Node *) lfirst(l));
		nargs++;
	}
	
	appendStringInfo(buf, "%s(",
					 generate_function_name(funcoid, nargs, argtypes));

2346 2347 2348
	sep = "";
	foreach(l, expr->args)
	{
2349
		appendStringInfo(buf, sep);
2350
		sep = ", ";
2351
		get_rule_expr((Node *) lfirst(l), context);
2352
	}
2353
	appendStringInfoChar(buf, ')');
2354 2355
}

2356
/*
2357 2358 2359 2360 2361 2362
 * get_agg_expr			- Parse back an Aggref node
 */
static void
get_agg_expr(Aggref *aggref, deparse_context *context)
{
	StringInfo	buf = context->buf;
2363
	Oid			argtype = exprType(aggref->target);
2364 2365

	appendStringInfo(buf, "%s(%s",
2366
					 generate_function_name(aggref->aggfnoid, 1, &argtype),
2367 2368 2369 2370 2371 2372 2373 2374
					 aggref->aggdistinct ? "DISTINCT " : "");
	if (aggref->aggstar)
		appendStringInfo(buf, "*");
	else
		get_rule_expr(aggref->target, context);
	appendStringInfoChar(buf, ')');
}

2375

2376 2377 2378 2379 2380
/*
 * strip_type_coercion
 *		Strip any type coercions at the top of the given expression tree,
 *		as long as they are coercions to the given datatype.
 *
2381 2382 2383
 * A RelabelType node is always a type coercion.  A function call is
 * also considered a type coercion if it has one argument and there is
 * a cast declared that uses it.
2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396
 *
 * XXX It'd be better if the parsetree retained some explicit indication
 * of the coercion, so we didn't need these heuristics.
 */
static Node *
strip_type_coercion(Node *expr, Oid resultType)
{
	if (expr == NULL || exprType(expr) != resultType)
		return expr;

	if (IsA(expr, RelabelType))
		return strip_type_coercion(((RelabelType *) expr)->arg, resultType);

2397 2398
	if (IsA(expr, Expr) &&
		((Expr *) expr)->opType == FUNC_EXPR)
2399 2400 2401
	{
		Func	   *func;
		HeapTuple	procTuple;
2402
		HeapTuple	castTuple;
2403
		Form_pg_proc procStruct;
2404
		Form_pg_cast castStruct;
2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418

		func = (Func *) (((Expr *) expr)->oper);
		Assert(IsA(func, Func));
		if (length(((Expr *) expr)->args) != 1)
			return expr;
		/* Lookup the function in pg_proc */
		procTuple = SearchSysCache(PROCOID,
								   ObjectIdGetDatum(func->funcid),
								   0, 0, 0);
		if (!HeapTupleIsValid(procTuple))
			elog(ERROR, "cache lookup for proc %u failed", func->funcid);
		procStruct = (Form_pg_proc) GETSTRUCT(procTuple);
		/* Double-check func has one arg and correct result type */
		if (procStruct->pronargs != 1 ||
2419
			procStruct->prorettype != resultType)
2420 2421 2422 2423
		{
			ReleaseSysCache(procTuple);
			return expr;
		}
2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
		/* See if function has is actually declared as a cast */
		castTuple = SearchSysCache(CASTSOURCETARGET,
								   ObjectIdGetDatum(procStruct->proargtypes[0]),
								   ObjectIdGetDatum(procStruct->prorettype),
								   0, 0);
		if (!HeapTupleIsValid(castTuple))
		{
			ReleaseSysCache(procTuple);
			return expr;
		}
		/* It must also be an implicit cast. */
		castStruct = (Form_pg_cast) GETSTRUCT(castTuple);
		if (!castStruct->castimplicit)
2437 2438
		{
			ReleaseSysCache(procTuple);
2439
			ReleaseSysCache(castTuple);
2440 2441 2442 2443
			return expr;
		}
		/* Okay, it is indeed a type-coercion function */
		ReleaseSysCache(procTuple);
2444
		ReleaseSysCache(castTuple);
2445 2446 2447 2448 2449 2450 2451
		return strip_type_coercion(lfirst(((Expr *) expr)->args), resultType);
	}

	return expr;
}


2452
/* ----------
2453 2454
 * get_tle_expr
 *
2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467
 *		In an INSERT or UPDATE targetlist item, the parser may have inserted
 *		a length-coercion function call to coerce the value to the right
 *		length for the target column.  We want to suppress the output of
 *		that function call, otherwise dump/reload/dump... would blow up the
 *		expression by adding more and more layers of length-coercion calls.
 *
 * As of 7.0, this hack is no longer absolutely essential, because the parser
 * is now smart enough not to add a redundant length coercion function call.
 * But we still suppress the function call just for neatness of displayed
 * rules.
 *
 * Note that this hack must NOT be applied to SELECT targetlist items;
 * any length coercion appearing there is something the user actually wrote.
2468 2469
 * ----------
 */
2470
static void
2471
get_tle_expr(TargetEntry *tle, deparse_context *context)
2472
{
2473
	Expr	   *expr = (Expr *) (tle->expr);
2474
	int32		coercedTypmod;
2475

2476
	/*
2477 2478
	 * If top level is a length coercion to the correct length, suppress
	 * it; else dump the expression normally.
2479
	 */
2480 2481 2482 2483 2484
	if (tle->resdom->restypmod >= 0 &&
		exprIsLengthCoercion((Node *) expr, &coercedTypmod) &&
		coercedTypmod == tle->resdom->restypmod)
		get_rule_expr((Node *) lfirst(expr->args), context);
	else
2485
		get_rule_expr(tle->expr, context);
2486 2487 2488 2489
}


/* ----------
2490 2491
 * get_const_expr
 *
2492
 *	Make a string representation of a Const
2493 2494
 * ----------
 */
2495
static void
2496
get_const_expr(Const *constval, deparse_context *context)
2497
{
2498
	StringInfo	buf = context->buf;
2499 2500 2501
	HeapTuple	typetup;
	Form_pg_type typeStruct;
	char	   *extval;
2502
	char	   *valptr;
2503

2504 2505 2506
	if (constval->constisnull)
	{
		/*
2507 2508
		 * Always label the type of a NULL constant to prevent misdecisions
		 * about type when reparsing.
2509
		 */
2510 2511
		appendStringInfo(buf, "NULL::%s",
						 format_type_with_typemod(constval->consttype, -1));
2512 2513 2514
		return;
	}

2515 2516 2517 2518 2519 2520 2521 2522
	typetup = SearchSysCache(TYPEOID,
							 ObjectIdGetDatum(constval->consttype),
							 0, 0, 0);
	if (!HeapTupleIsValid(typetup))
		elog(ERROR, "cache lookup of type %u failed", constval->consttype);

	typeStruct = (Form_pg_type) GETSTRUCT(typetup);

2523
	extval = DatumGetCString(OidFunctionCall3(typeStruct->typoutput,
2524 2525 2526
											  constval->constvalue,
								   ObjectIdGetDatum(typeStruct->typelem),
											  Int32GetDatum(-1)));
2527

2528
	switch (constval->consttype)
2529
	{
2530 2531 2532 2533
		case INT2OID:
		case INT4OID:
		case OIDOID:			/* int types */
		case FLOAT4OID:
2534
		case FLOAT8OID:			/* float types */
2535 2536 2537 2538
			/* These types are printed without quotes */
			appendStringInfo(buf, extval);
			break;
		default:
2539

2540 2541
			/*
			 * We must quote any funny characters in the constant's
2542
			 * representation. XXX Any MULTIBYTE considerations here?
2543 2544 2545 2546
			 */
			appendStringInfoChar(buf, '\'');
			for (valptr = extval; *valptr; valptr++)
			{
2547 2548
				char		ch = *valptr;

2549 2550 2551 2552 2553
				if (ch == '\'' || ch == '\\')
				{
					appendStringInfoChar(buf, '\\');
					appendStringInfoChar(buf, ch);
				}
2554
				else if (((unsigned char) ch) < ((unsigned char) ' '))
2555 2556 2557 2558 2559 2560
					appendStringInfo(buf, "\\%03o", (int) ch);
				else
					appendStringInfoChar(buf, ch);
			}
			appendStringInfoChar(buf, '\'');
			break;
2561 2562 2563
	}

	pfree(extval);
2564 2565 2566 2567 2568 2569 2570 2571 2572

	switch (constval->consttype)
	{
		case INT4OID:
		case FLOAT8OID:
		case UNKNOWNOID:
			/* These types can be left unlabeled */
			break;
		default:
2573 2574 2575
			appendStringInfo(buf, "::%s",
							 format_type_with_typemod(constval->consttype,
													  -1));
2576 2577
			break;
	}
2578 2579

	ReleaseSysCache(typetup);
2580 2581 2582 2583 2584 2585 2586
}


/* ----------
 * get_sublink_expr			- Parse back a sublink
 * ----------
 */
2587
static void
2588
get_sublink_expr(Node *node, deparse_context *context)
2589
{
2590
	StringInfo	buf = context->buf;
2591 2592 2593 2594
	SubLink    *sublink = (SubLink *) node;
	Query	   *query = (Query *) (sublink->subselect);
	List	   *l;
	char	   *sep;
2595 2596
	Oper	   *oper;
	bool		need_paren;
2597

2598
	appendStringInfoChar(buf, '(');
2599

2600
	if (sublink->lefthand != NIL)
2601
	{
2602 2603
		need_paren = (length(sublink->lefthand) > 1);
		if (need_paren)
2604
			appendStringInfoChar(buf, '(');
2605 2606 2607 2608

		sep = "";
		foreach(l, sublink->lefthand)
		{
2609
			appendStringInfo(buf, sep);
2610
			sep = ", ";
2611
			get_rule_expr((Node *) lfirst(l), context);
2612 2613
		}

2614
		if (need_paren)
2615
			appendStringInfo(buf, ") ");
2616
		else
2617
			appendStringInfoChar(buf, ' ');
2618 2619
	}

2620 2621
	need_paren = true;

2622 2623 2624 2625 2626 2627
	/*
	 * XXX we assume here that we can get away without qualifying the
	 * operator name.  Since the name may imply multiple physical operators
	 * it's rather difficult to do otherwise --- in fact, if the operators
	 * are in different namespaces any attempt to qualify would surely fail.
	 */
Bruce Momjian's avatar
Bruce Momjian committed
2628 2629
	switch (sublink->subLinkType)
	{
2630
		case EXISTS_SUBLINK:
2631
			appendStringInfo(buf, "EXISTS ");
2632 2633 2634
			break;

		case ANY_SUBLINK:
2635
			oper = (Oper *) lfirst(sublink->oper);
2636
			appendStringInfo(buf, "%s ANY ", get_opname(oper->opno));
2637 2638 2639
			break;

		case ALL_SUBLINK:
2640
			oper = (Oper *) lfirst(sublink->oper);
2641
			appendStringInfo(buf, "%s ALL ", get_opname(oper->opno));
2642 2643
			break;

2644
		case MULTIEXPR_SUBLINK:
2645
			oper = (Oper *) lfirst(sublink->oper);
2646
			appendStringInfo(buf, "%s ", get_opname(oper->opno));
2647 2648
			break;

2649 2650 2651 2652
		case EXPR_SUBLINK:
			need_paren = false;
			break;

2653
		default:
2654
			elog(ERROR, "get_sublink_expr: unsupported sublink type %d",
Bruce Momjian's avatar
Bruce Momjian committed
2655
				 sublink->subLinkType);
2656 2657 2658
			break;
	}

2659
	if (need_paren)
2660
		appendStringInfoChar(buf, '(');
2661

2662
	get_query_def(query, buf, context->namespaces, NULL);
2663 2664 2665 2666

	if (need_paren)
		appendStringInfo(buf, "))");
	else
2667
		appendStringInfoChar(buf, ')');
2668 2669
}

2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683

/* ----------
 * get_from_clause			- Parse back a FROM clause
 * ----------
 */
static void
get_from_clause(Query *query, deparse_context *context)
{
	StringInfo	buf = context->buf;
	char	   *sep;
	List	   *l;

	/*
	 * We use the query's jointree as a guide to what to print.  However,
2684 2685 2686 2687
	 * we must ignore auto-added RTEs that are marked not inFromCl. (These
	 * can only appear at the top level of the jointree, so it's
	 * sufficient to check here.) Also ignore the rule pseudo-RTEs for NEW
	 * and OLD.
2688 2689 2690
	 */
	sep = " FROM ";

2691
	foreach(l, query->jointree->fromlist)
2692
	{
2693
		Node	   *jtnode = (Node *) lfirst(l);
2694 2695 2696 2697 2698 2699 2700 2701

		if (IsA(jtnode, RangeTblRef))
		{
			int			varno = ((RangeTblRef *) jtnode)->rtindex;
			RangeTblEntry *rte = rt_fetch(varno, query->rtable);

			if (!rte->inFromCl)
				continue;
2702
			if (strcmp(rte->eref->aliasname, "*NEW*") == 0)
2703
				continue;
2704
			if (strcmp(rte->eref->aliasname, "*OLD*") == 0)
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723
				continue;
		}

		appendStringInfo(buf, sep);
		get_from_clause_item(jtnode, query, context);
		sep = ", ";
	}
}

static void
get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
{
	StringInfo	buf = context->buf;

	if (IsA(jtnode, RangeTblRef))
	{
		int			varno = ((RangeTblRef *) jtnode)->rtindex;
		RangeTblEntry *rte = rt_fetch(varno, query->rtable);

2724
		switch (rte->rtekind)
2725
		{
2726 2727 2728 2729
			case RTE_RELATION:
				/* Normal relation RTE */
				appendStringInfo(buf, "%s%s",
								 only_marker(rte),
2730
								 generate_relation_name(rte->relid));
2731 2732 2733 2734
				break;
			case RTE_SUBQUERY:
				/* Subquery RTE */
				appendStringInfoChar(buf, '(');
2735
				get_query_def(rte->subquery, buf, context->namespaces, NULL);
2736 2737
				appendStringInfoChar(buf, ')');
				break;
2738 2739 2740 2741
			case RTE_FUNCTION:
				/* Function RTE */
				get_rule_expr(rte->funcexpr, context);
				break;
2742 2743 2744
			default:
				elog(ERROR, "unexpected rte kind %d", (int) rte->rtekind);
				break;
2745
		}
2746 2747 2748
		if (rte->alias != NULL)
		{
			appendStringInfo(buf, " %s",
2749 2750
							 quote_identifier(rte->alias->aliasname));
			if (rte->alias->colnames != NIL)
2751 2752 2753
			{
				List	   *col;

2754
				appendStringInfo(buf, "(");
2755
				foreach(col, rte->alias->colnames)
2756
				{
2757
					if (col != rte->alias->colnames)
2758 2759
						appendStringInfo(buf, ", ");
					appendStringInfo(buf, "%s",
2760
								  quote_identifier(strVal(lfirst(col))));
2761 2762 2763 2764
				}
				appendStringInfoChar(buf, ')');
			}
		}
2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776
		else if (rte->rtekind == RTE_RELATION &&
				 strcmp(rte->eref->aliasname, get_rel_name(rte->relid)) != 0)
		{
			/*
			 * Apparently the rel has been renamed since the rule was made.
			 * Emit a fake alias clause so that variable references will
			 * still work.  This is not a 100% solution but should work in
			 * most reasonable situations.
			 */
			appendStringInfo(buf, " %s",
							 quote_identifier(rte->eref->aliasname));
		}
2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;

		appendStringInfoChar(buf, '(');
		get_from_clause_item(j->larg, query, context);
		if (j->isNatural)
			appendStringInfo(buf, " NATURAL");
		switch (j->jointype)
		{
			case JOIN_INNER:
				if (j->quals)
					appendStringInfo(buf, " JOIN ");
				else
					appendStringInfo(buf, " CROSS JOIN ");
				break;
			case JOIN_LEFT:
				appendStringInfo(buf, " LEFT JOIN ");
				break;
			case JOIN_FULL:
				appendStringInfo(buf, " FULL JOIN ");
				break;
			case JOIN_RIGHT:
				appendStringInfo(buf, " RIGHT JOIN ");
				break;
			case JOIN_UNION:
				appendStringInfo(buf, " UNION JOIN ");
				break;
			default:
				elog(ERROR, "get_from_clause_item: unknown join type %d",
					 (int) j->jointype);
		}
		get_from_clause_item(j->rarg, query, context);
2811
		if (!j->isNatural)
2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822
		{
			if (j->using)
			{
				List	   *col;

				appendStringInfo(buf, " USING (");
				foreach(col, j->using)
				{
					if (col != j->using)
						appendStringInfo(buf, ", ");
					appendStringInfo(buf, "%s",
2823
								  quote_identifier(strVal(lfirst(col))));
2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838
				}
				appendStringInfoChar(buf, ')');
			}
			else if (j->quals)
			{
				appendStringInfo(buf, " ON (");
				get_rule_expr(j->quals, context);
				appendStringInfoChar(buf, ')');
			}
		}
		appendStringInfoChar(buf, ')');
		/* Yes, it's correct to put alias after the right paren ... */
		if (j->alias != NULL)
		{
			appendStringInfo(buf, " %s",
2839 2840
							 quote_identifier(j->alias->aliasname));
			if (j->alias->colnames != NIL)
2841 2842 2843
			{
				List	   *col;

2844
				appendStringInfo(buf, "(");
2845
				foreach(col, j->alias->colnames)
2846
				{
2847
					if (col != j->alias->colnames)
2848 2849
						appendStringInfo(buf, ", ");
					appendStringInfo(buf, "%s",
2850
								  quote_identifier(strVal(lfirst(col))));
2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
				}
				appendStringInfoChar(buf, ')');
			}
		}
	}
	else
		elog(ERROR, "get_from_clause_item: unexpected node type %d",
			 nodeTag(jtnode));
}

2861
/*
2862 2863 2864
 * get_opclass_name			- fetch name of an index operator class
 *
 * The opclass name is appended (after a space) to buf.
2865 2866 2867 2868
 *
 * Output is suppressed if the opclass is the default for the given
 * actual_datatype.  (If you don't want this behavior, just pass
 * InvalidOid for actual_datatype.)
2869 2870
 */
static void
2871
get_opclass_name(Oid opclass, Oid actual_datatype,
2872 2873 2874 2875
				 StringInfo buf)
{
	HeapTuple	ht_opc;
	Form_pg_opclass opcrec;
2876 2877
	char	   *opcname;
	char	   *nspname;
2878

2879 2880 2881 2882
	/* Domains use their base type's default opclass */
	if (OidIsValid(actual_datatype))
		actual_datatype = getBaseType(actual_datatype);

2883 2884 2885 2886 2887 2888
	ht_opc = SearchSysCache(CLAOID,
							ObjectIdGetDatum(opclass),
							0, 0, 0);
	if (!HeapTupleIsValid(ht_opc))
		elog(ERROR, "cache lookup failed for opclass %u", opclass);
	opcrec = (Form_pg_opclass) GETSTRUCT(ht_opc);
2889
	if (actual_datatype != opcrec->opcintype || !opcrec->opcdefault)
2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902
	{
		/* Okay, we need the opclass name.  Do we need to qualify it? */
		opcname = NameStr(opcrec->opcname);
		if (OpclassIsVisible(opclass))
			appendStringInfo(buf, " %s", quote_identifier(opcname));
		else
		{
			nspname = get_namespace_name(opcrec->opcnamespace);
			appendStringInfo(buf, " %s.%s",
							 quote_identifier(nspname),
							 quote_identifier(opcname));
		}
	}
2903 2904
	ReleaseSysCache(ht_opc);
}
2905

2906
/*
2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918
 * tleIsArrayAssign			- check for array assignment
 */
static bool
tleIsArrayAssign(TargetEntry *tle)
{
	ArrayRef   *aref;

	if (tle->expr == NULL || !IsA(tle->expr, ArrayRef))
		return false;
	aref = (ArrayRef *) tle->expr;
	if (aref->refassgnexpr == NULL)
		return false;
2919

2920 2921 2922 2923 2924 2925
	/*
	 * Currently, it should only be possible to see non-null refassgnexpr
	 * if we are indeed looking at an "UPDATE array[n] = expr" situation.
	 * So aref->refexpr ought to match the tle's target.
	 */
	if (aref->refexpr == NULL || !IsA(aref->refexpr, Var) ||
2926
		((Var *) aref->refexpr)->varattno != tle->resdom->resno)
Bruce Momjian's avatar
Bruce Momjian committed
2927
		elog(WARNING, "tleIsArrayAssign: I'm confused ...");
2928 2929 2930
	return true;
}

2931
/*
2932 2933 2934 2935 2936
 * quote_identifier			- Quote an identifier only if needed
 *
 * When quotes are needed, we palloc the required space; slightly
 * space-wasteful but well worth it for notational simplicity.
 */
2937 2938
const char *
quote_identifier(const char *ident)
2939 2940
{
	/*
2941 2942
	 * Can avoid quoting if ident starts with a lowercase letter or underscore
	 * and contains only lowercase letters, digits, and underscores, *and* is
2943
	 * not any SQL keyword.  Otherwise, supply quotes.
2944
	 */
2945
	int			nquotes = 0;
2946
	bool		safe;
2947
	const char *ptr;
2948
	char	   *result;
2949
	char	   *optr;
2950 2951 2952 2953 2954

	/*
	 * would like to use <ctype.h> macros here, but they might yield
	 * unwanted locale-specific results...
	 */
2955
	safe = ((ident[0] >= 'a' && ident[0] <= 'z') || ident[0] == '_');
2956 2957

	for (ptr = ident; *ptr; ptr++)
2958
	{
2959
		char		ch = *ptr;
2960

2961 2962 2963
		if ((ch >= 'a' && ch <= 'z') ||
			(ch >= '0' && ch <= '9') ||
			(ch == '_'))
2964
		{
2965 2966 2967 2968 2969 2970 2971
			/* okay */
		}
		else
		{
			safe = false;
			if (ch == '"')
				nquotes++;
2972 2973 2974
		}
	}

2975 2976 2977 2978 2979 2980 2981 2982
	if (safe)
	{
		/*
		 * Check for keyword.  This test is overly strong, since many of
		 * the "keywords" known to the parser are usable as column names,
		 * but the parser doesn't provide any easy way to test for whether
		 * an identifier is safe or not... so be safe not sorry.
		 *
2983 2984
		 * Note: ScanKeywordLookup() does case-insensitive comparison, but
		 * that's fine, since we already know we have all-lower-case.
2985
		 */
2986
		if (ScanKeywordLookup(ident) != NULL)
2987 2988 2989
			safe = false;
	}

2990 2991 2992
	if (safe)
		return ident;			/* no change needed */

2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007
	result = (char *) palloc(strlen(ident) + nquotes + 2 + 1);

	optr = result;
	*optr++ = '"';
	for (ptr = ident; *ptr; ptr++)
	{
		char		ch = *ptr;

		if (ch == '"')
			*optr++ = '"';
		*optr++ = ch;
	}
	*optr++ = '"';
	*optr = '\0';

3008 3009
	return result;
}
3010

3011
/*
3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029
 * quote_qualified_identifier	- Quote a possibly-qualified identifier
 *
 * Return a name of the form namespace.ident, or just ident if namespace
 * is NULL, quoting each component if necessary.  The result is palloc'd.
 */
char *
quote_qualified_identifier(const char *namespace,
						   const char *ident)
{
	StringInfoData buf;

	initStringInfo(&buf);
	if (namespace)
		appendStringInfo(&buf, "%s.", quote_identifier(namespace));
	appendStringInfo(&buf, "%s", quote_identifier(ident));
	return buf.data;
}

3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191
/*
 * generate_relation_name
 *		Compute the name to display for a relation specified by OID
 *
 * The result includes all necessary quoting and schema-prefixing.
 */
static char *
generate_relation_name(Oid relid)
{
	HeapTuple	tp;
	Form_pg_class reltup;
	char	   *nspname;
	char	   *result;

	tp = SearchSysCache(RELOID,
						ObjectIdGetDatum(relid),
						0, 0, 0);
	if (!HeapTupleIsValid(tp))
		elog(ERROR, "cache lookup of relation %u failed", relid);
	reltup = (Form_pg_class) GETSTRUCT(tp);

	/* Qualify the name if not visible in search path */
	if (RelationIsVisible(relid))
		nspname = NULL;
	else
		nspname = get_namespace_name(reltup->relnamespace);

	result = quote_qualified_identifier(nspname, NameStr(reltup->relname));

	ReleaseSysCache(tp);

	return result;
}

/*
 * generate_function_name
 *		Compute the name to display for a function specified by OID,
 *		given that it is being called with the specified actual arg types.
 *		(Arg types matter because of ambiguous-function resolution rules.)
 *
 * The result includes all necessary quoting and schema-prefixing.
 */
static char *
generate_function_name(Oid funcid, int nargs, Oid *argtypes)
{
	HeapTuple	proctup;
	Form_pg_proc procform;
	char	   *proname;
	char	   *nspname;
	char	   *result;
	FuncDetailCode p_result;
	Oid			p_funcid;
	Oid			p_rettype;
	bool		p_retset;
	Oid		   *p_true_typeids;

	proctup = SearchSysCache(PROCOID,
							 ObjectIdGetDatum(funcid),
							 0, 0, 0);
	if (!HeapTupleIsValid(proctup))
		elog(ERROR, "cache lookup of function %u failed", funcid);
	procform = (Form_pg_proc) GETSTRUCT(proctup);
	proname = NameStr(procform->proname);
	Assert(nargs == procform->pronargs);

	/*
	 * The idea here is to schema-qualify only if the parser would fail to
	 * resolve the correct function given the unqualified func name
	 * with the specified argtypes.
	 */
	p_result = func_get_detail(makeList1(makeString(proname)),
							   NIL, nargs, argtypes,
							   &p_funcid, &p_rettype,
							   &p_retset, &p_true_typeids);
	if (p_result != FUNCDETAIL_NOTFOUND && p_funcid == funcid)
		nspname = NULL;
	else
		nspname = get_namespace_name(procform->pronamespace);

	result = quote_qualified_identifier(nspname, proname);

	ReleaseSysCache(proctup);

	return result;
}

/*
 * generate_operator_name
 *		Compute the name to display for an operator specified by OID,
 *		given that it is being called with the specified actual arg types.
 *		(Arg types matter because of ambiguous-operator resolution rules.
 *		Pass InvalidOid for unused arg of a unary operator.)
 *
 * The result includes all necessary quoting and schema-prefixing,
 * plus the OPERATOR() decoration needed to use a qualified operator name
 * in an expression.
 */
static char *
generate_operator_name(Oid operid, Oid arg1, Oid arg2)
{
	StringInfoData buf;
	HeapTuple	opertup;
	Form_pg_operator operform;
	char	   *oprname;
	char	   *nspname;
	Operator	p_result;

	initStringInfo(&buf);

	opertup = SearchSysCache(OPEROID,
							 ObjectIdGetDatum(operid),
							 0, 0, 0);
	if (!HeapTupleIsValid(opertup))
		elog(ERROR, "cache lookup of operator %u failed", operid);
	operform = (Form_pg_operator) GETSTRUCT(opertup);
	oprname = NameStr(operform->oprname);

	/*
	 * The idea here is to schema-qualify only if the parser would fail to
	 * resolve the correct operator given the unqualified op name
	 * with the specified argtypes.
	 */
	switch (operform->oprkind)
	{
		case 'b':
			p_result = oper(makeList1(makeString(oprname)), arg1, arg2, true);
			break;
		case 'l':
			p_result = left_oper(makeList1(makeString(oprname)), arg2, true);
			break;
		case 'r':
			p_result = right_oper(makeList1(makeString(oprname)), arg1, true);
			break;
		default:
			elog(ERROR, "unexpected oprkind %c for operator %u",
				 operform->oprkind, operid);
			p_result = NULL;	/* keep compiler quiet */
			break;
	}

	if (p_result != NULL && oprid(p_result) == operid)
		nspname = NULL;
	else
	{
		nspname = get_namespace_name(operform->oprnamespace);
		appendStringInfo(&buf, "OPERATOR(%s.", quote_identifier(nspname));
	}

	appendStringInfo(&buf, "%s", oprname);

	if (nspname)
		appendStringInfoChar(&buf, ')');

	if (p_result != NULL)
		ReleaseSysCache(p_result);

	ReleaseSysCache(opertup);

	return buf.data;
}

/*
3192 3193 3194 3195 3196
 * get_relid_attribute_name
 *		Get an attribute name by its relations Oid and its attnum
 *
 * Same as underlying syscache routine get_attname(), except that error
 * is handled by elog() instead of returning NULL.
3197 3198
 */
static char *
3199
get_relid_attribute_name(Oid relid, AttrNumber attnum)
3200
{
3201
	char	   *attname;
3202

3203 3204
	attname = get_attname(relid, attnum);
	if (attname == NULL)
3205
		elog(ERROR, "cache lookup of attribute %d in relation %u failed",
3206
			 attnum, relid);
3207 3208
	return attname;
}