summaryrefslogtreecommitdiff
path: root/src/backend/utils/adt/ruleutils.c
blob: c4e31491604f556433878f6794fdde7ff162b5f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
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
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
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
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
/**********************************************************************
 * get_ruledef.c	- Function to get a rules definition text
 *			  out of its tuple
 *
 * IDENTIFICATION
 *	  $Header: /cvsroot/pgsql/src/backend/utils/adt/ruleutils.c,v 1.39 2000/01/15 22:43:24 tgl Exp $
 *
 *	  This software is copyrighted by Jan Wieck - Hamburg.
 *
 *	  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.
 *
 *	  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.
 *
 *	  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.
 *
 **********************************************************************/

#include <unistd.h>
#include <fcntl.h>

#include "postgres.h"

#include "catalog/pg_index.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_shadow.h"
#include "catalog/pg_type.h"
#include "executor/spi.h"
#include "lib/stringinfo.h"
#include "optimizer/clauses.h"
#include "optimizer/tlist.h"
#include "parser/keywords.h"
#include "parser/parsetree.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"


/* ----------
 * Local data types
 * ----------
 */
typedef struct
{
	StringInfo	buf;			/* output buffer to append to */
	List	   *rangetables;	/* List of List of RangeTblEntry */
	bool		varprefix;		/* TRUE to print prefixes on Vars */
} deparse_context;

typedef struct {
	Index		rt_index;
	int			levelsup;
} check_if_rte_used_context;


/* ----------
 * Global data
 * ----------
 */
static char *rulename = NULL;
static void *plan_getrule = NULL;
static char *query_getrule = "SELECT * FROM pg_rewrite WHERE rulename = $1";
static void *plan_getview = NULL;
static char *query_getview = "SELECT * FROM pg_rewrite WHERE rulename = $1 or rulename = $2";
static void *plan_getam = NULL;
static char *query_getam = "SELECT * FROM pg_am WHERE oid = $1";
static void *plan_getopclass = NULL;
static char *query_getopclass = "SELECT * FROM pg_opclass WHERE oid = $1";


/* ----------
 * Local functions
 *
 * 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.
 * ----------
 */
static void make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc);
static void make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc);
static void get_query_def(Query *query, StringInfo buf, List *parentrtables);
static void get_select_query_def(Query *query, deparse_context *context);
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);
static RangeTblEntry *get_rte_for_var(Var *var, deparse_context *context);
static void get_rule_expr(Node *node, deparse_context *context);
static void get_func_expr(Expr *expr, deparse_context *context);
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);
static char *quote_identifier(char *ident);
static char *get_relation_name(Oid relid);
static char *get_attribute_name(Oid relid, int2 attnum);
static bool check_if_rte_used(Node *node, Index rt_index, int levelsup);
static bool check_if_rte_used_walker(Node *node,
									 check_if_rte_used_context *context);

#define inherit_marker(rte)  ((rte)->inh ? "*" : "")


/* ----------
 * get_ruledef			- Do it all and return a text
 *				  that could be used as a statement
 *				  to recreate the rule
 * ----------
 */
text *
pg_get_ruledef(NameData *rname)
{
	text	   *ruledef;
	Datum		args[1];
	char		nulls[2];
	int			spirc;
	HeapTuple	ruletup;
	TupleDesc	rulettc;
	StringInfoData	buf;
	int			len;

	/* ----------
	 * We need the rules name somewhere deep down
	 * ----------
	 */
	rulename = pstrdup(NameStr(*rname));

	/* ----------
	 * Connect to SPI manager
	 * ----------
	 */
	if (SPI_connect() != SPI_OK_CONNECT)
		elog(ERROR, "get_ruledef: cannot connect to SPI manager");

	/* ----------
	 * On the first call prepare the plan to lookup pg_proc.
	 * We read pg_proc over the SPI manager instead of using
	 * the syscache to be checked for read access on pg_proc.
	 * ----------
	 */
	if (plan_getrule == NULL)
	{
		Oid			argtypes[1];
		void	   *plan;

		argtypes[0] = NAMEOID;
		plan = SPI_prepare(query_getrule, 1, argtypes);
		if (plan == NULL)
			elog(ERROR, "SPI_prepare() failed for \"%s\"", query_getrule);
		plan_getrule = SPI_saveplan(plan);
	}

	/* ----------
	 * Get the pg_rewrite tuple for this rule
	 * ----------
	 */
	args[0] = PointerGetDatum(rulename);
	nulls[0] = (rulename == NULL) ? 'n' : ' ';
	nulls[1] = '\0';
	spirc = SPI_execp(plan_getrule, args, nulls, 1);
	if (spirc != SPI_OK_SELECT)
		elog(ERROR, "failed to get pg_rewrite tuple for %s", rulename);
	if (SPI_processed != 1)
	{
		if (SPI_finish() != SPI_OK_FINISH)
			elog(ERROR, "get_ruledef: SPI_finish() failed");
		ruledef = SPI_palloc(VARHDRSZ + 1);
		VARSIZE(ruledef) = VARHDRSZ + 1;
		VARDATA(ruledef)[0] = '-';
		return ruledef;
	}

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

	/* ----------
	 * Get the rules definition and put it into executors memory
	 * ----------
	 */
	initStringInfo(&buf);
	make_ruledef(&buf, ruletup, rulettc);
	len = buf.len + VARHDRSZ;
	ruledef = SPI_palloc(len);
	VARSIZE(ruledef) = len;
	memcpy(VARDATA(ruledef), buf.data, buf.len);
	pfree(buf.data);

	/* ----------
	 * Disconnect from SPI manager
	 * ----------
	 */
	if (SPI_finish() != SPI_OK_FINISH)
		elog(ERROR, "get_ruledef: SPI_finish() failed");

	/* ----------
	 * Easy - isn't it?
	 * ----------
	 */
	return ruledef;
}


/* ----------
 * get_viewdef			- Mainly the same thing, but we
 *				  only return the SELECT part of a view
 * ----------
 */
text *
pg_get_viewdef(NameData *rname)
{
	text	   *ruledef;
	Datum		args[2];
	char		nulls[3];
	int			spirc;
	HeapTuple	ruletup;
	TupleDesc	rulettc;
	StringInfoData	buf;
	int			len;
	char		name1[NAMEDATALEN + 5];
	char		name2[NAMEDATALEN + 5];

	/* ----------
	 * We need the rules name somewhere deep down
	 * ----------
	 */
	rulename = pstrdup(NameStr(*rname));

	/* ----------
	 * Connect to SPI manager
	 * ----------
	 */
	if (SPI_connect() != SPI_OK_CONNECT)
		elog(ERROR, "get_viewdef: cannot connect to SPI manager");

	/* ----------
	 * On the first call prepare the plan to lookup pg_proc.
	 * We read pg_proc over the SPI manager instead of using
	 * the syscache to be checked for read access on pg_proc.
	 * ----------
	 */
	if (plan_getview == NULL)
	{
		Oid			argtypes[2];
		void	   *plan;

		argtypes[0] = NAMEOID;
		argtypes[1] = NAMEOID;
		plan = SPI_prepare(query_getview, 2, argtypes);
		if (plan == NULL)
			elog(ERROR, "SPI_prepare() failed for \"%s\"", query_getview);
		plan_getview = SPI_saveplan(plan);
	}

	/* ----------
	 * Get the pg_rewrite tuple for this rule
	 * ----------
	 */
	sprintf(name1, "_RET%s", rulename);
	sprintf(name2, "_ret%s", rulename);
	args[0] = PointerGetDatum(name1);
	args[1] = PointerGetDatum(name2);
	nulls[0] = ' ';
	nulls[1] = ' ';
	nulls[2] = '\0';
	spirc = SPI_execp(plan_getview, args, nulls, 1);
	if (spirc != SPI_OK_SELECT)
		elog(ERROR, "failed to get pg_rewrite tuple for view %s", rulename);
	initStringInfo(&buf);
	if (SPI_processed != 1)
		appendStringInfo(&buf, "Not a view");
	else
	{
		/* ----------
		 * Get the rules definition and put it into executors memory
		 * ----------
		 */
		ruletup = SPI_tuptable->vals[0];
		rulettc = SPI_tuptable->tupdesc;
		make_viewdef(&buf, ruletup, rulettc);
	}
	len = buf.len + VARHDRSZ;
	ruledef = SPI_palloc(len);
	VARSIZE(ruledef) = len;
	memcpy(VARDATA(ruledef), buf.data, buf.len);
	pfree(buf.data);

	/* ----------
	 * Disconnect from SPI manager
	 * ----------
	 */
	if (SPI_finish() != SPI_OK_FINISH)
		elog(ERROR, "get_viewdef: SPI_finish() failed");

	/* ----------
	 * Easy - isn't it?
	 * ----------
	 */
	return ruledef;
}


/* ----------
 * get_indexdef			- Get the definition of an index
 * ----------
 */
text *
pg_get_indexdef(Oid indexrelid)
{
	text	   *indexdef;
	HeapTuple	ht_idx;
	HeapTuple	ht_idxrel;
	HeapTuple	ht_indrel;
	HeapTuple	spi_tup;
	TupleDesc	spi_ttc;
	int			spi_fno;
	Form_pg_index idxrec;
	Form_pg_class idxrelrec;
	Form_pg_class indrelrec;
	Datum		spi_args[1];
	char		spi_nulls[2];
	int			spirc;
	int			len;
	int			keyno;
	StringInfoData	buf;
	StringInfoData	keybuf;
	char	   *sep;

	/* ----------
	 * Connect to SPI manager
	 * ----------
	 */
	if (SPI_connect() != SPI_OK_CONNECT)
		elog(ERROR, "get_indexdef: cannot connect to SPI manager");

	/* ----------
	 * On the first call prepare the plans to lookup pg_am
	 * and pg_opclass.
	 * ----------
	 */
	if (plan_getam == NULL)
	{
		Oid			argtypes[1];
		void	   *plan;

		argtypes[0] = OIDOID;
		plan = SPI_prepare(query_getam, 1, argtypes);
		if (plan == NULL)
			elog(ERROR, "SPI_prepare() failed for \"%s\"", query_getam);
		plan_getam = SPI_saveplan(plan);

		argtypes[0] = OIDOID;
		plan = SPI_prepare(query_getopclass, 1, argtypes);
		if (plan == NULL)
			elog(ERROR, "SPI_prepare() failed for \"%s\"", query_getopclass);
		plan_getopclass = SPI_saveplan(plan);
	}

	/* ----------
	 * Fetch the pg_index tuple by the Oid of the index
	 * ----------
	 */
	ht_idx = SearchSysCacheTuple(INDEXRELID,
								 ObjectIdGetDatum(indexrelid), 0, 0, 0);
	if (!HeapTupleIsValid(ht_idx))
		elog(ERROR, "syscache lookup for index %u failed", indexrelid);
	idxrec = (Form_pg_index) GETSTRUCT(ht_idx);

	/* ----------
	 * Fetch the pg_class tuple of the index relation
	 * ----------
	 */
	ht_idxrel = SearchSysCacheTuple(RELOID,
						  ObjectIdGetDatum(idxrec->indexrelid), 0, 0, 0);
	if (!HeapTupleIsValid(ht_idxrel))
		elog(ERROR, "syscache lookup for relid %u failed", idxrec->indexrelid);
	idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);

	/* ----------
	 * Fetch the pg_class tuple of the indexed relation
	 * ----------
	 */
	ht_indrel = SearchSysCacheTuple(RELOID,
							ObjectIdGetDatum(idxrec->indrelid), 0, 0, 0);
	if (!HeapTupleIsValid(ht_indrel))
		elog(ERROR, "syscache lookup for relid %u failed", idxrec->indrelid);
	indrelrec = (Form_pg_class) GETSTRUCT(ht_indrel);

	/* ----------
	 * Get the am name for the index relation
	 * ----------
	 */
	spi_args[0] = ObjectIdGetDatum(idxrelrec->relam);
	spi_nulls[0] = ' ';
	spi_nulls[1] = '\0';
	spirc = SPI_execp(plan_getam, spi_args, spi_nulls, 1);
	if (spirc != SPI_OK_SELECT)
		elog(ERROR, "failed to get pg_am tuple for index %s",
			 NameStr(idxrelrec->relname));
	if (SPI_processed != 1)
		elog(ERROR, "failed to get pg_am tuple for index %s",
			 NameStr(idxrelrec->relname));
	spi_tup = SPI_tuptable->vals[0];
	spi_ttc = SPI_tuptable->tupdesc;
	spi_fno = SPI_fnumber(spi_ttc, "amname");

	/* ----------
	 * Start the index definition
	 * ----------
	 */
	initStringInfo(&buf);
	appendStringInfo(&buf, "CREATE %sINDEX %s ON %s USING %s (",
					 idxrec->indisunique ? "UNIQUE " : "",
					 quote_identifier(pstrdup(NameStr(idxrelrec->relname))),
					 quote_identifier(pstrdup(NameStr(indrelrec->relname))),
					 quote_identifier(SPI_getvalue(spi_tup, spi_ttc,
												   spi_fno)));

	/* ----------
	 * Collect the indexed attributes
	 * ----------
	 */
	initStringInfo(&keybuf);
	sep = "";
	for (keyno = 0; keyno < INDEX_MAX_KEYS; keyno++)
	{
		if (idxrec->indkey[keyno] == InvalidAttrNumber)
			break;

		appendStringInfo(&keybuf, sep);
		sep = ", ";

		/* ----------
		 * Add the indexed field name
		 * ----------
		 */
		appendStringInfo(&keybuf, "%s",
				quote_identifier(get_attribute_name(idxrec->indrelid,
													idxrec->indkey[keyno])));

		/* ----------
		 * If not a functional index, add the operator class name
		 * ----------
		 */
		if (idxrec->indproc == InvalidOid)
		{
			spi_args[0] = ObjectIdGetDatum(idxrec->indclass[keyno]);
			spi_nulls[0] = ' ';
			spi_nulls[1] = '\0';
			spirc = SPI_execp(plan_getopclass, spi_args, spi_nulls, 1);
			if (spirc != SPI_OK_SELECT)
				elog(ERROR, "failed to get pg_opclass tuple %u", idxrec->indclass[keyno]);
			if (SPI_processed != 1)
				elog(ERROR, "failed to get pg_opclass tuple %u", idxrec->indclass[keyno]);
			spi_tup = SPI_tuptable->vals[0];
			spi_ttc = SPI_tuptable->tupdesc;
			spi_fno = SPI_fnumber(spi_ttc, "opcname");
			appendStringInfo(&keybuf, " %s",
							 quote_identifier(SPI_getvalue(spi_tup, spi_ttc,
														   spi_fno)));
		}
	}

	/* ----------
	 * For functional index say 'func (attrs) opclass'
	 * ----------
	 */
	if (idxrec->indproc != InvalidOid)
	{
		HeapTuple	proctup;
		Form_pg_proc procStruct;

		proctup = SearchSysCacheTuple(PROCOID,
							 ObjectIdGetDatum(idxrec->indproc), 0, 0, 0);
		if (!HeapTupleIsValid(proctup))
			elog(ERROR, "cache lookup for proc %u failed", idxrec->indproc);

		procStruct = (Form_pg_proc) GETSTRUCT(proctup);
		appendStringInfo(&buf, "%s(%s) ",
						 quote_identifier(pstrdup(NameStr(procStruct->proname))),
						 keybuf.data);

		spi_args[0] = ObjectIdGetDatum(idxrec->indclass[0]);
		spi_nulls[0] = ' ';
		spi_nulls[1] = '\0';
		spirc = SPI_execp(plan_getopclass, spi_args, spi_nulls, 1);
		if (spirc != SPI_OK_SELECT)
			elog(ERROR, "failed to get pg_opclass tuple %u", idxrec->indclass[0]);
		if (SPI_processed != 1)
			elog(ERROR, "failed to get pg_opclass tuple %u", idxrec->indclass[0]);
		spi_tup = SPI_tuptable->vals[0];
		spi_ttc = SPI_tuptable->tupdesc;
		spi_fno = SPI_fnumber(spi_ttc, "opcname");
		appendStringInfo(&buf, "%s",
						 quote_identifier(SPI_getvalue(spi_tup, spi_ttc,
													   spi_fno)));
	}
	else
		/* ----------
		 * For the others say 'attr opclass [, ...]'
		 * ----------
		 */
		appendStringInfo(&buf, "%s", keybuf.data);

	/* ----------
	 * Finish
	 * ----------
	 */
	appendStringInfo(&buf, ")");

	/* ----------
	 * Create the result in upper executor memory
	 * ----------
	 */
	len = buf.len + VARHDRSZ;
	indexdef = SPI_palloc(len);
	VARSIZE(indexdef) = len;
	memcpy(VARDATA(indexdef), buf.data, buf.len);
	pfree(buf.data);
	pfree(keybuf.data);

	/* ----------
	 * Disconnect from SPI manager
	 * ----------
	 */
	if (SPI_finish() != SPI_OK_FINISH)
		elog(ERROR, "get_viewdef: SPI_finish() failed");

	return indexdef;
}


/* ----------
 * get_userbyid			- Get a user name by usesysid and
 *				  fallback to 'unknown (UID=n)'
 * ----------
 */
NameData   *
pg_get_userbyid(int32 uid)
{
	HeapTuple	usertup;
	Form_pg_shadow user_rec;
	NameData   *result;

	/* ----------
	 * Allocate space for the result
	 * ----------
	 */
	result = (NameData *) palloc(NAMEDATALEN);
	memset(NameStr(*result), 0, NAMEDATALEN);

	/* ----------
	 * Get the pg_shadow entry and print the result
	 * ----------
	 */
	usertup = SearchSysCacheTuple(SHADOWSYSID,
								  ObjectIdGetDatum(uid), 0, 0, 0);
	if (HeapTupleIsValid(usertup))
	{
		user_rec = (Form_pg_shadow) GETSTRUCT(usertup);
		StrNCpy(NameStr(*result), NameStr(user_rec->usename), NAMEDATALEN);
	}
	else
		sprintf((char *) result, "unknown (UID=%d)", uid);

	return result;
}

/* ----------
 * 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).
 *
 * rangetables is a List of Lists of RangeTblEntry nodes: first sublist is for
 * varlevelsup = 0, next for varlevelsup = 1, etc.  In each sublist the first
 * item is for varno = 1, next varno = 2, etc.  (Each sublist has the same
 * format as the rtable list of a parsetree or query.)
 *
 * forceprefix is TRUE to force all Vars to be prefixed with their table names.
 * Otherwise, a prefix is printed only if there's more than one table involved
 * (and someday the code might try to print one only if there's ambiguity).
 *
 * The result is a palloc'd string.
 * ----------
 */
char *
deparse_expression(Node *expr, List *rangetables, bool forceprefix)
{
	StringInfoData	buf;
	deparse_context	context;

	initStringInfo(&buf);
	context.buf = &buf;
	context.rangetables = rangetables;
	context.varprefix = (forceprefix ||
						 length(rangetables) != 1 ||
						 length((List *) lfirst(rangetables)) != 1);

	rulename = "";				/* in case of errors */

	get_rule_expr(expr, &context);

	return buf.data;
}

/* ----------
 * make_ruledef			- reconstruct the CREATE RULE command
 *				  for a given pg_rewrite tuple
 * ----------
 */
static void
make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc)
{
	char		ev_type;
	Oid			ev_class;
	int2		ev_attr;
	bool		is_instead;
	char	   *ev_qual;
	char	   *ev_action;
	List	   *actions = NIL;
	int			fno;
	bool		isnull;

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


	/* ----------
	 * Build the rules definition text
	 * ----------
	 */
	appendStringInfo(buf, "CREATE RULE %s AS ON ",
					 quote_identifier(rulename));

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

		case '2':
			appendStringInfo(buf, "UPDATE");
			break;

		case '3':
			appendStringInfo(buf, "INSERT");
			break;

		case '4':
			appendStringInfo(buf, "DELETE");
			break;

		default:
			elog(ERROR, "get_ruledef: rule %s has unsupported event type %d",
				 rulename, ev_type);
			break;
	}

	/* The relation the rule is fired on */
	appendStringInfo(buf, " TO %s",
					 quote_identifier(get_relation_name(ev_class)));
	if (ev_attr > 0)
		appendStringInfo(buf, ".%s",
						 quote_identifier(get_attribute_name(ev_class,
															 ev_attr)));

	/* If the rule has an event qualification, add it */
	if (ev_qual == NULL)
		ev_qual = "";
	if (strlen(ev_qual) > 0 && strcmp(ev_qual, "<>") != 0)
	{
		Node	   *qual;
		Query	   *query;
		deparse_context	context;

		appendStringInfo(buf, " WHERE ");

		qual = stringToNode(ev_qual);
		query = (Query *) lfirst(actions);

		context.buf = buf;
		context.rangetables = lcons(query->rtable, NIL);
		context.varprefix = (length(query->rtable) != 1);

		get_rule_expr(qual, &context);
	}

	appendStringInfo(buf, " DO ");

	/* The INSTEAD keyword (if so) */
	if (is_instead)
		appendStringInfo(buf, "INSTEAD ");

	/* Finally the rules actions */
	if (length(actions) > 1)
	{
		List	   *action;
		Query	   *query;

		appendStringInfo(buf, "(");
		foreach(action, actions)
		{
			query = (Query *) lfirst(action);
			get_query_def(query, buf, NIL);
			appendStringInfo(buf, "; ");
		}
		appendStringInfo(buf, ");");
	}
	else
	{
		if (length(actions) == 0)
		{
			appendStringInfo(buf, "NOTHING;");
		}
		else
		{
			Query	   *query;

			query = (Query *) lfirst(actions);
			get_query_def(query, buf, NIL);
			appendStringInfo(buf, ";");
		}
	}
}


/* ----------
 * make_viewdef			- reconstruct the SELECT part of a
 *				  view rewrite rule
 * ----------
 */
static void
make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc)
{
	Query	   *query;
	char		ev_type;
	Oid			ev_class;
	int2		ev_attr;
	bool		is_instead;
	char	   *ev_qual;
	char	   *ev_action;
	List	   *actions = NIL;
	int			fno;
	bool		isnull;

	/* ----------
	 * 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)
	{
		appendStringInfo(buf, "Not a view");
		return;
	}

	query = (Query *) lfirst(actions);

	if (ev_type != '1' || ev_attr >= 0 || !is_instead || strcmp(ev_qual, "<>"))
	{
		appendStringInfo(buf, "Not a view");
		return;
	}

	get_query_def(query, buf, NIL);
	appendStringInfo(buf, ";");
}


/* ----------
 * get_query_def			- Parse back one action from
 *					  the parsetree in the actions
 *					  list
 * ----------
 */
static void
get_query_def(Query *query, StringInfo buf, List *parentrtables)
{
	deparse_context	context;

	context.buf = buf;
	context.rangetables = lcons(query->rtable, parentrtables);
	context.varprefix = (parentrtables != NIL ||
						 length(query->rtable) != 1);

	switch (query->commandType)
	{
		case CMD_SELECT:
			get_select_query_def(query, &context);
			break;

		case CMD_UPDATE:
			get_update_query_def(query, &context);
			break;

		case CMD_INSERT:
			get_insert_query_def(query, &context);
			break;

		case CMD_DELETE:
			get_delete_query_def(query, &context);
			break;

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

		default:
			elog(ERROR, "get_ruledef of %s: query command type %d not implemented yet",
				 rulename, query->commandType);
			break;
	}
}


/* ----------
 * get_select_query_def			- Parse back a SELECT parsetree
 * ----------
 */
static void
get_select_query_def(Query *query, deparse_context *context)
{
	StringInfo	buf = context->buf;
	char	   *sep;
	TargetEntry *tle;
	RangeTblEntry *rte;
	bool	   *rt_used;
	int			rt_length;
	int			rt_numused = 0;
	bool		rt_constonly = TRUE;
	int			i;
	List	   *l;

	/* ----------
	 * First we need to know which and how many of the
	 * range table entries in the query are used in the target list
	 * or queries qualification
	 * ----------
	 */
	rt_length = length(query->rtable);
	rt_used = palloc(sizeof(bool) * rt_length);
	for (i = 0; i < rt_length; i++)
	{
		if (check_if_rte_used((Node *) (query->targetList), i + 1, 0) ||
			check_if_rte_used(query->qual, i + 1, 0) ||
			check_if_rte_used(query->havingQual, i + 1, 0))
		{
			rt_used[i] = TRUE;
			rt_numused++;
		}
		else
			rt_used[i] = FALSE;
	}

	/* ----------
	 * Now check if any of the used rangetable entries is different
	 * from *NEW* and *CURRENT*. If so we must provide the FROM clause
	 * later.
	 * ----------
	 */
	i = 0;
	foreach(l, query->rtable)
	{
		if (!rt_used[i++])
			continue;

		rte = (RangeTblEntry *) lfirst(l);
		if (!strcmp(rte->refname, "*NEW*"))
			continue;
		if (!strcmp(rte->refname, "*CURRENT*"))
			continue;

		rt_constonly = FALSE;
		break;
	}

	/* ----------
	 * Build up the query string - first we say SELECT
	 * ----------
	 */
	appendStringInfo(buf, "SELECT");

	/* Then we tell what to select (the targetlist) */
	sep = " ";
	foreach(l, query->targetList)
	{
		bool		tell_as = FALSE;

		tle = (TargetEntry *) lfirst(l);
		appendStringInfo(buf, sep);
		sep = ", ";

		get_tle_expr(tle, context);

		/* Check if we must say AS ... */
		if (! IsA(tle->expr, Var))
			tell_as = strcmp(tle->resdom->resname, "?column?");
		else
		{
			Var		   *var = (Var *) (tle->expr);
			char	   *attname;

			rte = get_rte_for_var(var, context);
			attname = get_attribute_name(rte->relid, var->varattno);
			if (strcmp(attname, tle->resdom->resname))
				tell_as = TRUE;
		}

		/* and do if so */
		if (tell_as)
			appendStringInfo(buf, " AS %s",
							 quote_identifier(tle->resdom->resname));
	}

	/* If we need other tables than *NEW* or *CURRENT* add the FROM clause */
	if (!rt_constonly && rt_numused > 0)
	{
		sep = " FROM ";
		i = 0;
		foreach(l, query->rtable)
		{
			if (rt_used[i++])
			{
				rte = (RangeTblEntry *) lfirst(l);

				if (!strcmp(rte->refname, "*NEW*"))
					continue;

				if (!strcmp(rte->refname, "*CURRENT*"))
					continue;

				appendStringInfo(buf, sep);
				sep = ", ";
				appendStringInfo(buf, "%s%s",
								 quote_identifier(rte->relname),
								 inherit_marker(rte));
				if (strcmp(rte->relname, rte->refname) != 0)
					appendStringInfo(buf, " %s",
									 quote_identifier(rte->refname));
			}
		}
	}

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

	/* Add the GROUP BY CLAUSE */
	if (query->groupClause != NULL)
	{
		appendStringInfo(buf, " GROUP BY ");
		sep = "";
		foreach(l, query->groupClause)
		{
			GroupClause *grp = (GroupClause *) lfirst(l);
			Node *groupexpr;

			groupexpr = get_sortgroupclause_expr(grp,
												 query->targetList);
			appendStringInfo(buf, sep);
			get_rule_expr(groupexpr, context);
			sep = ", ";
		}
	}
}


/* ----------
 * get_insert_query_def			- Parse back an INSERT parsetree
 * ----------
 */
static void
get_insert_query_def(Query *query, deparse_context *context)
{
	StringInfo	buf = context->buf;
	char	   *sep;
	TargetEntry *tle;
	RangeTblEntry *rte;
	bool	   *rt_used;
	int			rt_length;
	int			rt_numused = 0;
	bool		rt_constonly = TRUE;
	int			i;
	List	   *l;

	/* ----------
	 * We need to know if other tables than *NEW* or *CURRENT*
	 * are used in the query. If not, it's an INSERT ... VALUES,
	 * otherwise an INSERT ... SELECT.
	 * ----------
	 */
	rt_length = length(query->rtable);
	rt_used = palloc(sizeof(bool) * rt_length);
	for (i = 0; i < rt_length; i++)
	{
		if (check_if_rte_used((Node *) (query->targetList), i + 1, 0) ||
			check_if_rte_used(query->qual, i + 1, 0) ||
			check_if_rte_used(query->havingQual, i + 1, 0))
		{
			rt_used[i] = TRUE;
			rt_numused++;
		}
		else
			rt_used[i] = FALSE;
	}

	i = 0;
	foreach(l, query->rtable)
	{
		if (!rt_used[i++])
			continue;

		rte = (RangeTblEntry *) lfirst(l);
		if (!strcmp(rte->refname, "*NEW*"))
			continue;
		if (!strcmp(rte->refname, "*CURRENT*"))
			continue;

		rt_constonly = FALSE;
		break;
	}

	/* ----------
	 * Start the query with INSERT INTO relname
	 * ----------
	 */
	rte = rt_fetch(query->resultRelation, query->rtable);
	appendStringInfo(buf, "INSERT INTO %s",
					 quote_identifier(rte->relname));

	/* Add the target list */
	sep = " (";
	foreach(l, query->targetList)
	{
		tle = (TargetEntry *) lfirst(l);

		appendStringInfo(buf, sep);
		sep = ", ";
		appendStringInfo(buf, "%s", quote_identifier(tle->resdom->resname));
	}
	appendStringInfo(buf, ") ");

	/* Add the VALUES or the SELECT */
	if (rt_constonly && query->qual == NULL)
	{
		appendStringInfo(buf, "VALUES (");
		sep = "";
		foreach(l, query->targetList)
		{
			tle = (TargetEntry *) lfirst(l);

			appendStringInfo(buf, sep);
			sep = ", ";
			get_tle_expr(tle, context);
		}
		appendStringInfo(buf, ")");
	}
	else
		get_select_query_def(query, context);
}


/* ----------
 * get_update_query_def			- Parse back an UPDATE parsetree
 * ----------
 */
static void
get_update_query_def(Query *query, deparse_context *context)
{
	StringInfo	buf = context->buf;
	char	   *sep;
	TargetEntry *tle;
	RangeTblEntry *rte;
	List	   *l;

	/* ----------
	 * Start the query with UPDATE relname SET
	 * ----------
	 */
	rte = rt_fetch(query->resultRelation, query->rtable);
	appendStringInfo(buf, "UPDATE %s%s SET ",
					 quote_identifier(rte->relname),
					 inherit_marker(rte));

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

		appendStringInfo(buf, sep);
		sep = ", ";
		appendStringInfo(buf, "%s = ",
						 quote_identifier(tle->resdom->resname));
		get_tle_expr(tle, context);
	}

	/* Finally add a WHERE clause if given */
	if (query->qual != NULL)
	{
		appendStringInfo(buf, " WHERE ");
		get_rule_expr(query->qual, context);
	}
}


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

	/* ----------
	 * Start the query with DELETE FROM relname
	 * ----------
	 */
	rte = rt_fetch(query->resultRelation, query->rtable);
	appendStringInfo(buf, "DELETE FROM %s%s",
					 quote_identifier(rte->relname),
					 inherit_marker(rte));

	/* Add a WHERE clause if given */
	if (query->qual != NULL)
	{
		appendStringInfo(buf, " WHERE ");
		get_rule_expr(query->qual, context);
	}
}

/*
 * Find the RTE referenced by a (possibly nonlocal) Var.
 */
static RangeTblEntry *
get_rte_for_var(Var *var, deparse_context *context)
{
	List   *rtlist = context->rangetables;
	int		sup = var->varlevelsup;

	while (sup-- > 0)
		rtlist = lnext(rtlist);

	return rt_fetch(var->varno, (List *) lfirst(rtlist));
}


/* ----------
 * get_rule_expr			- Parse back an expression
 * ----------
 */
static void
get_rule_expr(Node *node, deparse_context *context)
{
	StringInfo	buf = context->buf;

	if (node == NULL)
		return;

	/* ----------
	 * Each level of get_rule_expr must emit an indivisible term
	 * (parenthesized if necessary) to ensure result is reparsed into
	 * the same expression tree.
	 *
	 * There might be some work left here to support additional node types.
	 * Can we ever see Param nodes here?
	 * ----------
	 */
	switch (nodeTag(node))
	{
		case T_Const:
			get_const_expr((Const *) node, context);
			break;

		case T_Var:
			{
				Var		   *var = (Var *) node;
				RangeTblEntry *rte = get_rte_for_var(var, context);

				if (context->varprefix)
				{
					if (!strcmp(rte->refname, "*NEW*"))
						appendStringInfo(buf, "new.");
					else if (!strcmp(rte->refname, "*CURRENT*"))
						appendStringInfo(buf, "old.");
					else
						appendStringInfo(buf, "%s.",
										 quote_identifier(rte->refname));
				}
				appendStringInfo(buf, "%s",
						quote_identifier(get_attribute_name(rte->relid,
															var->varattno)));
			}
			break;

		case T_Expr:
			{
				Expr	   *expr = (Expr *) node;
				List	   *args = expr->args;

				/* ----------
				 * Expr nodes have to be handled a bit detailed
				 * ----------
				 */
				switch (expr->opType)
				{
					case OP_EXPR:
						appendStringInfo(buf, "(");
						if (length(args) == 2)
						{
							/* binary operator */
							get_rule_expr((Node *) lfirst(args), context);
							appendStringInfo(buf, " %s ",
									get_opname(((Oper *) expr->oper)->opno));
							get_rule_expr((Node *) lsecond(args), context);
						}
						else
						{
							/* unary operator --- but which side? */
							Oid			opno = ((Oper *) expr->oper)->opno;
							HeapTuple	tp;
							Form_pg_operator optup;

							tp = SearchSysCacheTuple(OPEROID,
													 ObjectIdGetDatum(opno),
													 0, 0, 0);
							Assert(HeapTupleIsValid(tp));
							optup = (Form_pg_operator) GETSTRUCT(tp);
							switch (optup->oprkind)
							{
								case 'l':
									appendStringInfo(buf, "%s ",
													 get_opname(opno));
									get_rule_expr((Node *) lfirst(args),
												  context);
									break;
								case 'r':
									get_rule_expr((Node *) lfirst(args),
												  context);
									appendStringInfo(buf, " %s",
													 get_opname(opno));
									break;
								default:
									elog(ERROR, "get_rule_expr: bogus oprkind");
							}
						}
						appendStringInfo(buf, ")");
						break;

					case OR_EXPR:
						appendStringInfo(buf, "(");
						get_rule_expr((Node *) lfirst(args), context);
						while ((args = lnext(args)) != NIL)
						{
							appendStringInfo(buf, " OR ");
							get_rule_expr((Node *) lfirst(args), context);
						}
						appendStringInfo(buf, ")");
						break;

					case AND_EXPR:
						appendStringInfo(buf, "(");
						get_rule_expr((Node *) lfirst(args), context);
						while ((args = lnext(args)) != NIL)
						{
							appendStringInfo(buf, " AND ");
							get_rule_expr((Node *) lfirst(args), context);
						}
						appendStringInfo(buf, ")");
						break;

					case NOT_EXPR:
						appendStringInfo(buf, "(NOT ");
						get_rule_expr((Node *) lfirst(args), context);
						appendStringInfo(buf, ")");
						break;

					case FUNC_EXPR:
						get_func_expr((Expr *) node, context);
						break;

					default:
						elog(ERROR, "get_rule_expr: expr opType %d not supported",
							 expr->opType);
				}
			}
			break;

		case T_Aggref:
			{
				Aggref	   *aggref = (Aggref *) node;

				appendStringInfo(buf, "%s(%s",
								 quote_identifier(aggref->aggname),
								 aggref->aggdistinct ? "DISTINCT " : "");
				if (aggref->aggstar)
					appendStringInfo(buf, "*");
				else
					get_rule_expr(aggref->target, context);
				appendStringInfo(buf, ")");
			}
			break;

		case T_Iter:
			get_rule_expr(((Iter *) node)->iterexpr, context);
			break;

		case T_ArrayRef:
			{
				ArrayRef   *aref = (ArrayRef *) node;
				List	   *lowlist;
				List	   *uplist;

				get_rule_expr(aref->refexpr, context);
				lowlist = aref->reflowerindexpr;
				foreach(uplist, aref->refupperindexpr)
				{
					appendStringInfo(buf, "[");
					if (lowlist)
					{
						get_rule_expr((Node *) lfirst(lowlist), context);
						appendStringInfo(buf, ":");
						lowlist = lnext(lowlist);
					}
					get_rule_expr((Node *) lfirst(uplist), context);
					appendStringInfo(buf, "]");
				}
				/* XXX need to do anything with refassgnexpr? */
			}
			break;

		case T_CaseExpr:
			{
				CaseExpr   *caseexpr = (CaseExpr *) node;
				List	   *temp;

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

					appendStringInfo(buf, " WHEN ");
					get_rule_expr(when->expr, context);
					appendStringInfo(buf, " THEN ");
					get_rule_expr(when->result, context);
				}
				appendStringInfo(buf, " ELSE ");
				get_rule_expr(caseexpr->defresult, context);
				appendStringInfo(buf, " END");
			}
			break;

		case T_SubLink:
			get_sublink_expr(node, context);
			break;

		default:
			printf("\n%s\n", nodeToString(node));
			elog(ERROR, "get_ruledef of %s: unknown node type %d in get_rule_expr()",
				 rulename, nodeTag(node));
			break;
	}
}


/* ----------
 * get_func_expr			- Parse back a Func node
 * ----------
 */
static void
get_func_expr(Expr *expr, deparse_context *context)
{
	StringInfo	buf = context->buf;
	HeapTuple	proctup;
	Form_pg_proc procStruct;
	List	   *l;
	char	   *sep;
	Func	   *func = (Func *) (expr->oper);
	char	   *proname;

	/* ----------
	 * Get the functions pg_proc tuple
	 * ----------
	 */
	proctup = SearchSysCacheTuple(PROCOID,
								  ObjectIdGetDatum(func->funcid),
								  0, 0, 0);
	if (!HeapTupleIsValid(proctup))
		elog(ERROR, "cache lookup for proc %u failed", func->funcid);

	procStruct = (Form_pg_proc) GETSTRUCT(proctup);
	proname = pstrdup(NameStr(procStruct->proname));

	/*
	 * nullvalue() and nonnullvalue() should get turned into special syntax
	 */
	if (procStruct->pronargs == 1 && procStruct->proargtypes[0] == InvalidOid)
	{
		if (!strcmp(proname, "nullvalue"))
		{
			appendStringInfo(buf, "(");
			get_rule_expr((Node *) lfirst(expr->args), context);
			appendStringInfo(buf, " ISNULL)");
			return;
		}
		if (!strcmp(proname, "nonnullvalue"))
		{
			appendStringInfo(buf, "(");
			get_rule_expr((Node *) lfirst(expr->args), context);
			appendStringInfo(buf, " NOTNULL)");
			return;
		}
	}

	/* ----------
	 * Build a string of proname(args)
	 * ----------
	 */
	appendStringInfo(buf, "%s(", quote_identifier(proname));
	sep = "";
	foreach(l, expr->args)
	{
		appendStringInfo(buf, sep);
		sep = ", ";
		get_rule_expr((Node *) lfirst(l), context);
	}
	appendStringInfo(buf, ")");
}


/* ----------
 * get_tle_expr
 *
 *		A target list expression is a bit different from a normal expression.
 *		If the target column has an atttypmod, the parser usually puts a
 *		padding-/cut-function call around the expression itself.
 *		We must get rid of it, otherwise dump/reload/dump... would blow up
 *		the expressions.
 * ----------
 */
static void
get_tle_expr(TargetEntry *tle, deparse_context *context)
{
	Expr	   *expr = (Expr *) (tle->expr);
	Func	   *func;
	HeapTuple	tup;
	Form_pg_proc procStruct;
	Form_pg_type typeStruct;
	Const	   *second_arg;

	/* ----------
	 * Check if the result has an atttypmod and if the
	 * expression in the targetlist entry is a function call
	 * ----------
	 */
	if (tle->resdom->restypmod < 0 ||
		! IsA(expr, Expr) ||
		expr->opType != FUNC_EXPR)
	{
		get_rule_expr(tle->expr, context);
		return;
	}

	func = (Func *) (expr->oper);

	/* ----------
	 * Get the functions pg_proc tuple
	 * ----------
	 */
	tup = SearchSysCacheTuple(PROCOID,
							  ObjectIdGetDatum(func->funcid), 0, 0, 0);
	if (!HeapTupleIsValid(tup))
		elog(ERROR, "cache lookup for proc %u failed", func->funcid);
	procStruct = (Form_pg_proc) GETSTRUCT(tup);

	/* ----------
	 * It must be a function with two arguments where the first
	 * is of the same type as the return value and the second is
	 * an int4.
	 * ----------
	 */
	if (procStruct->pronargs != 2 ||
		procStruct->prorettype != procStruct->proargtypes[0] ||
		procStruct->proargtypes[1] != INT4OID)
	{
		get_rule_expr(tle->expr, context);
		return;
	}

	/*
	 * Furthermore, the name of the function must be the same
	 * as the argument/result type name.
	 */
	tup = SearchSysCacheTuple(TYPEOID,
							  ObjectIdGetDatum(procStruct->prorettype),
							  0, 0, 0);
	if (!HeapTupleIsValid(tup))
		elog(ERROR, "cache lookup for type %u failed",
			 procStruct->prorettype);
	typeStruct = (Form_pg_type) GETSTRUCT(tup);
	if (strncmp(NameStr(procStruct->proname),
				NameStr(typeStruct->typname),
				NAMEDATALEN) != 0)
	{
		get_rule_expr(tle->expr, context);
		return;
	}

	/* ----------
	 * Finally (to be totally safe) the second argument must be a
	 * const and match the value in the results atttypmod.
	 * ----------
	 */
	second_arg = (Const *) lsecond(expr->args);
	if (! IsA(second_arg, Const) ||
		DatumGetInt32(second_arg->constvalue) != tle->resdom->restypmod)
	{
		get_rule_expr(tle->expr, context);
		return;
	}

	/* ----------
	 * Whow - got it. Now get rid of the padding function
	 * ----------
	 */
	get_rule_expr((Node *) lfirst(expr->args), context);
}


/* ----------
 * get_const_expr
 *
 *	Make a string representation of a Const
 * ----------
 */
static void
get_const_expr(Const *constval, deparse_context *context)
{
	StringInfo	buf = context->buf;
	HeapTuple	typetup;
	Form_pg_type typeStruct;
	FmgrInfo	finfo_output;
	char	   *extval;
	char	   *valptr;

	typetup = SearchSysCacheTuple(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);

	if (constval->constisnull)
	{
		/*
		 * Always label the type of a NULL constant.  This not only
		 * prevents misdecisions about the type, but it ensures that
		 * our output is a valid b_expr.
		 */
		extval = pstrdup(NameStr(typeStruct->typname));
		appendStringInfo(buf, "NULL::%s", quote_identifier(extval));
		pfree(extval);
		return;
	}

	fmgr_info(typeStruct->typoutput, &finfo_output);
	extval = (char *) (*fmgr_faddr(&finfo_output)) (constval->constvalue,
													typeStruct->typelem,
													-1);

	switch (constval->consttype)
	{
		case INT2OID:
		case INT4OID:
		case OIDOID:			/* int types */
		case FLOAT4OID:
		case FLOAT8OID:			/* float types */
			/* These types are printed without quotes */
			appendStringInfo(buf, extval);
			break;
		default:
			/*
			 * We must quote any funny characters in the constant's
			 * representation.
			 * XXX Any MULTIBYTE considerations here?
			 */
			appendStringInfoChar(buf, '\'');
			for (valptr = extval; *valptr; valptr++)
			{
				char	ch = *valptr;
				if (ch == '\'' || ch == '\\')
				{
					appendStringInfoChar(buf, '\\');
					appendStringInfoChar(buf, ch);
				}
				else if (ch >= 0 && ch < ' ')
					appendStringInfo(buf, "\\%03o", (int) ch);
				else
					appendStringInfoChar(buf, ch);
			}
			appendStringInfoChar(buf, '\'');
			break;
	}

	pfree(extval);

	switch (constval->consttype)
	{
		case INT4OID:
		case FLOAT8OID:
		case UNKNOWNOID:
			/* These types can be left unlabeled */
			break;
		default:
			extval = pstrdup(NameStr(typeStruct->typname));
			appendStringInfo(buf, "::%s", quote_identifier(extval));
			pfree(extval);
			break;
	}
}


/* ----------
 * get_sublink_expr			- Parse back a sublink
 * ----------
 */
static void
get_sublink_expr(Node *node, deparse_context *context)
{
	StringInfo	buf = context->buf;
	SubLink    *sublink = (SubLink *) node;
	Query	   *query = (Query *) (sublink->subselect);
	List	   *l;
	char	   *sep;
	Oper	   *oper;
	bool		need_paren;

	appendStringInfo(buf, "(");

	if (sublink->lefthand != NIL)
	{
		need_paren = (length(sublink->lefthand) > 1);
		if (need_paren)
			appendStringInfo(buf, "(");

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

		if (need_paren)
			appendStringInfo(buf, ") ");
		else
			appendStringInfo(buf, " ");
	}

	need_paren = true;

	switch (sublink->subLinkType)
	{
		case EXISTS_SUBLINK:
			appendStringInfo(buf, "EXISTS ");
			break;

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

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

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

		case EXPR_SUBLINK:
			need_paren = false;
			break;

		default:
			elog(ERROR, "get_sublink_expr: unsupported sublink type %d",
				 sublink->subLinkType);
			break;
	}

	if (need_paren)
		appendStringInfo(buf, "(");

	get_query_def(query, buf, context->rangetables);

	if (need_paren)
		appendStringInfo(buf, "))");
	else
		appendStringInfo(buf, ")");
}

/* ----------
 * 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.
 * ----------
 */
static char *
quote_identifier(char *ident)
{
	/*
	 * Can avoid quoting if ident starts with a lowercase letter and
	 * contains only lowercase letters, digits, and underscores,
	 * *and* is not any SQL keyword.  Otherwise, supply quotes.
	 */
	bool		safe;
	char	   *result;

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

		for (ptr = ident+1; *ptr; ptr++)
		{
			char	ch = *ptr;

			safe = ((ch >= 'a' && ch <= 'z') ||
					(ch >= '0' && ch <= '9') ||
					(ch == '_'));
			if (! safe)
				break;
		}
	}

	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.
		 *
		 * Note: ScanKeywordLookup() expects an all-lower-case input, but
		 * we've already checked we have that.
		 */
		if (ScanKeywordLookup(ident) != NULL)
			safe = false;
	}

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

	result = (char *) palloc(strlen(ident) + 2 + 1);
	sprintf(result, "\"%s\"", ident);
	return result;
}

/* ----------
 * get_relation_name			- Get a relation name by Oid
 * ----------
 */
static char *
get_relation_name(Oid relid)
{
	HeapTuple	classtup;
	Form_pg_class classStruct;

	classtup = SearchSysCacheTuple(RELOID,
								   ObjectIdGetDatum(relid), 0, 0, 0);
	if (!HeapTupleIsValid(classtup))
		elog(ERROR, "cache lookup of relation %u failed", relid);

	classStruct = (Form_pg_class) GETSTRUCT(classtup);
	return pstrdup(NameStr(classStruct->relname));
}


/* ----------
 * get_attribute_name			- Get an attribute name by its
 *					  relations Oid and its attnum
 * ----------
 */
static char *
get_attribute_name(Oid relid, int2 attnum)
{
	HeapTuple	atttup;
	Form_pg_attribute attStruct;

	atttup = SearchSysCacheTuple(ATTNUM,
								 ObjectIdGetDatum(relid), (Datum) attnum,
								 0, 0);
	if (!HeapTupleIsValid(atttup))
		elog(ERROR, "cache lookup of attribute %d in relation %u failed",
			 attnum, relid);

	attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
	return pstrdup(NameStr(attStruct->attname));
}


/* ----------
 * check_if_rte_used
 *		Check a targetlist or qual to see if a given rangetable entry
 *		is used in it
 * ----------
 */
static bool
check_if_rte_used(Node *node, Index rt_index, int levelsup)
{
	check_if_rte_used_context context;

	context.rt_index = rt_index;
	context.levelsup = levelsup;
	return check_if_rte_used_walker(node, &context);
}

static bool
check_if_rte_used_walker(Node *node,
						 check_if_rte_used_context *context)
{
	if (node == NULL)
		return false;
	if (IsA(node, Var))
	{
		Var		   *var = (Var *) node;

		return var->varno == context->rt_index &&
			var->varlevelsup == context->levelsup;
	}
	if (IsA(node, SubLink))
	{
		SubLink    *sublink = (SubLink *) node;
		Query	   *query = (Query *) sublink->subselect;

		/* Recurse into subquery; expression_tree_walker will not */
		if (check_if_rte_used((Node *) (query->targetList),
							  context->rt_index, context->levelsup + 1) ||
			check_if_rte_used(query->qual,
							  context->rt_index, context->levelsup + 1) ||
			check_if_rte_used(query->havingQual,
							  context->rt_index, context->levelsup + 1))
			return true;
		/* fall through to let expression_tree_walker examine lefthand args */
	}
	return expression_tree_walker(node, check_if_rte_used_walker,
								  (void *) context);
}