Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
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
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
/*-------------------------------------------------------------------------
 *
 * heaptuple.c
 *    This file contains heap tuple accessor and mutator routines, as well
 *    as various tuple utilities.
 *
 * Some notes about varlenas and this code:
 *
 * Before Postgres 8.3 varlenas always had a 4-byte length header, and
 * therefore always needed 4-byte alignment (at least).  This wasted space
 * for short varlenas, for example CHAR(1) took 5 bytes and could need up to
 * 3 additional padding bytes for alignment.
 *
 * Now, a short varlena (up to 126 data bytes) is reduced to a 1-byte header
 * and we don't align it.  To hide this from datatype-specific functions that
 * don't want to deal with it, such a datum is considered "toasted" and will
 * be expanded back to the normal 4-byte-header format by pg_detoast_datum.
 * (In performance-critical code paths we can use pg_detoast_datum_packed
 * and the appropriate access macros to avoid that overhead.)  Note that this
 * conversion is performed directly in heap_form_tuple, without invoking
 * heaptoast.c.
 *
 * This change will break any code that assumes it needn't detoast values
 * that have been put into a tuple but never sent to disk.  Hopefully there
 * are few such places.
 *
 * Varlenas still have alignment INT (or DOUBLE) in pg_type/pg_attribute, since
 * that's the normal requirement for the untoasted format.  But we ignore that
 * for the 1-byte-header format.  This means that the actual start position
 * of a varlena datum may vary depending on which format it has.  To determine
 * what is stored, we have to require that alignment padding bytes be zero.
 * (Postgres actually has always zeroed them, but now it's required!)  Since
 * the first byte of a 1-byte-header varlena can never be zero, we can examine
 * the first byte after the previous datum to tell if it's a pad byte or the
 * start of a 1-byte-header varlena.
 *
 * Note that while formerly we could rely on the first varlena column of a
 * system catalog to be at the offset suggested by the C struct for the
 * catalog, this is now risky: it's only safe if the preceding field is
 * word-aligned, so that there will never be any padding.
 *
 * We don't pack varlenas whose attstorage is PLAIN, since the data type
 * isn't expecting to have to detoast values.  This is used in particular
 * by oidvector and int2vector, which are used in the system catalogs
 * and we'd like to still refer to them via C struct offsets.
 *
 *
 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
 *    src/backend/access/common/heaptuple.c
 *
 *-------------------------------------------------------------------------
 */
 
#include "postgres.h"
 
#include "access/heaptoast.h"
#include "access/sysattr.h"
#include "access/tupdesc_details.h"
#include "access/xlogdefs.h"
#include "catalog/pg_type_d.h"
#include "common/hashfn.h"
#include "common/int.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/expandeddatum.h"
#include "utils/hsearch.h"
#include "utils/memutils.h"
#include "utils/typcache.h"
 
 
/*
 * Does att's datatype allow packing into the 1-byte-header varlena format?
 * While functions that use TupleDescAttr() and assign attstorage =
 * TYPSTORAGE_PLAIN cannot use packed varlena headers, functions that call
 * TupleDescInitEntry() use typeForm->typstorage (TYPSTORAGE_EXTENDED) and
 * can use packed varlena headers, e.g.:
 *     CREATE TABLE test(a VARCHAR(10000) STORAGE PLAIN);
 *     INSERT INTO test VALUES (repeat('A',10));
 * This can be verified with pageinspect.
 */
#define ATT_IS_PACKABLE(att) \
    ((att)->attlen == -1 && (att)->attstorage != TYPSTORAGE_PLAIN)
/* Use this if it's already known varlena */
#define VARLENA_ATT_IS_PACKABLE(att) \
    ((att)->attstorage != TYPSTORAGE_PLAIN)
 
/* FormData_pg_attribute.attstorage != TYPSTORAGE_PLAIN and an attlen of -1 */
#define COMPACT_ATTR_IS_PACKABLE(att) \
    ((att)->attlen == -1 && (att)->attispackable)
 
 
static void heap_datum_check_coercion(HeapTupleHeader tup, TupleDesc targetDesc);
 
 
/* GUC variable */
int         composite_type_mismatch = COMPOSITE_TYPE_MISMATCH_ERROR;
 
 
/*
 * Setup for caching pass-by-ref missing attributes in a way that survives
 * tupleDesc destruction.
 */
 
typedef struct
{
    int         len;
    Datum       value;
} missing_cache_key;
 
static HTAB *missing_cache = NULL;
 
static uint32
missing_hash(const void *key, Size keysize)
{
    const missing_cache_key *entry = key;
 
    return hash_bytes((const unsigned char *) DatumGetPointer(entry->value), entry->len);
}
 
static int
missing_match(const void *key1, const void *key2, Size keysize)
{
    const missing_cache_key *entry1 = key1;
    const missing_cache_key *entry2 = key2;
 
    if (entry1->len != entry2->len)
        return entry1->len > entry2->len ? 1 : -1;
 
    return memcmp(DatumGetPointer(entry1->value),
                  DatumGetPointer(entry2->value),
                  entry1->len);
}
 
static void
init_missing_cache(void)
{
    HASHCTL     hash_ctl;
 
    hash_ctl.keysize = sizeof(missing_cache_key);
    hash_ctl.entrysize = sizeof(missing_cache_key);
    hash_ctl.hcxt = TopMemoryContext;
    hash_ctl.hash = missing_hash;
    hash_ctl.match = missing_match;
    missing_cache =
        hash_create("Missing Values Cache",
                    32,
                    &hash_ctl,
                    HASH_ELEM | HASH_CONTEXT | HASH_FUNCTION | HASH_COMPARE);
}
 
/* ----------------------------------------------------------------
 *                      misc support routines
 * ----------------------------------------------------------------
 */
 
/*
 * Return the missing value of an attribute, or NULL if there isn't one.
 */
Datum
getmissingattr(TupleDesc tupleDesc,
               int attnum, bool *isnull)
{
    CompactAttribute *att;
 
    Assert(attnum <= tupleDesc->natts);
    Assert(attnum > 0);
 
    att = TupleDescCompactAttr(tupleDesc, attnum - 1);
 
    if (att->atthasmissing)
    {
        AttrMissing *attrmiss;
 
        Assert(tupleDesc->constr);
        Assert(tupleDesc->constr->missing);
 
        attrmiss = tupleDesc->constr->missing + (attnum - 1);
 
        if (attrmiss->am_present)
        {
            missing_cache_key key;
            missing_cache_key *entry;
            bool        found;
            MemoryContext oldctx;
 
            *isnull = false;
 
            /* no  need to cache by-value attributes */
            if (att->attbyval)
                return attrmiss->am_value;
 
            /* set up cache if required */
            if (missing_cache == NULL)
                init_missing_cache();
 
            /* check if there's a cache entry */
            Assert(att->attlen > 0 || att->attlen == -1);
            if (att->attlen > 0)
                key.len = att->attlen;
            else
                key.len = VARSIZE_ANY(DatumGetPointer(attrmiss->am_value));
            key.value = attrmiss->am_value;
 
            entry = hash_search(missing_cache, &key, HASH_ENTER, &found);
 
            if (!found)
            {
                /* cache miss, so we need a non-transient copy of the datum */
                oldctx = MemoryContextSwitchTo(TopMemoryContext);
                entry->value =
                    datumCopy(attrmiss->am_value, false, att->attlen);
                MemoryContextSwitchTo(oldctx);
            }
 
            return entry->value;
        }
    }
 
    *isnull = true;
    return PointerGetDatum(NULL);
}
 
/*
 * heap_compute_data_size
 *      Determine size of the data area of a tuple to be constructed
 */
Size
heap_compute_data_size(TupleDesc tupleDesc,
                       const Datum *values,
                       const bool *isnull)
{
    return heap_compute_data_size_ext(tupleDesc, values, isnull, false);
}
 
/*
 * heap_compute_data_size_ext
 *      Determine size of the data area of a tuple to be constructed,
 *      potentially over MaxAllocSize
 *
 * If allow_huge is false, then we raise an error if any intermediate
 * result goes beyond MaxAllocSize; in 32-bit architectures we also
 * do that when the result of an addition overflows Size (which is 32-bit)
 */
Size
heap_compute_data_size_ext(TupleDesc tupleDesc,
                           const Datum *values,
                           const bool *isnull,
                           bool allow_huge)
{
    Size        data_length = 0;
    int         numberOfAttributes = tupleDesc->natts;
 
    for (int i = 0; i < numberOfAttributes; i++)
    {
        Datum       val;
        CompactAttribute *atti;
        bool        ovfl;
 
        if (isnull[i])
            continue;
 
        val = values[i];
        atti = TupleDescCompactAttr(tupleDesc, i);
 
        if (COMPACT_ATTR_IS_PACKABLE(atti) &&
            VARATT_CAN_MAKE_SHORT(DatumGetPointer(val)))
        {
            /*
             * we're anticipating converting to a short varlena header, so
             * adjust length and don't count any alignment
             */
            ovfl = pg_add_size_overflow(data_length,
                                        VARATT_CONVERTED_SHORT_SIZE(DatumGetPointer(val)),
                                        &data_length);
        }
        else if (atti->attlen == -1 &&
                 VARATT_IS_EXTERNAL_EXPANDED(DatumGetPointer(val)))
        {
            /*
             * we want to flatten the expanded value so that the constructed
             * tuple doesn't depend on it
             */
            data_length = att_nominal_alignby(data_length, atti->attalignby);
            ovfl = pg_add_size_overflow(data_length,
                                        EOH_get_flat_size(DatumGetEOHP(val)),
                                        &data_length);
        }
        else
        {
            data_length = att_datum_alignby(data_length, atti->attalignby,
                                            atti->attlen, val);
            data_length = att_addlength_datum_overflow(data_length, atti->attlen,
                                                       val, &ovfl);
        }
 
        /*
         * Unless caller allows huge values, prevent going beyond the palloc
         * limit.  In cases where caller does allow huge values, we can't
         * trust the AllocSizeIsValid() test alone on 32-bit platforms, which
         * is why we use overflow-detecting addition above.
         */
        if (ovfl || (!allow_huge && !AllocSizeIsValid(data_length)))
            ereport(ERROR,
                    errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                    errmsg("tuple is too big"));
    }
 
    return data_length;
}
 
/*
 * Per-attribute helper for heap_fill_tuple and other routines building tuples.
 *
 * Fill in either a data value or a bit in the null bitmask
 */
static inline void
fill_val(CompactAttribute *att,
         uint8 **bit,
         int *bitmask,
         char **dataP,
         uint16 *infomask,
         Datum datum,
         bool isnull)
{
    Size        data_length;
    char       *data = *dataP;
 
    /*
     * If we're building a null bitmap, set the appropriate bit for the
     * current column value here.
     */
    if (bit != NULL)
    {
        if (*bitmask != HIGHBIT)
            *bitmask <<= 1;
        else
        {
            *bit += 1;
            **bit = 0x0;
            *bitmask = 1;
        }
 
        if (isnull)
        {
            *infomask |= HEAP_HASNULL;
            return;
        }
 
        **bit |= *bitmask;
    }
 
    /*
     * XXX we use the att_nominal_alignby macro on the pointer value itself,
     * not on an offset.  This is a bit of a hack.
     */
    if (att->attbyval)
    {
        /* pass-by-value */
        data = (char *) att_nominal_alignby(data, att->attalignby);
        store_att_byval(data, datum, att->attlen);
        data_length = att->attlen;
    }
    else if (att->attlen == -1)
    {
        /* varlena */
        Pointer     val = DatumGetPointer(datum);
 
        *infomask |= HEAP_HASVARWIDTH;
        if (VARATT_IS_EXTERNAL(val))
        {
            if (VARATT_IS_EXTERNAL_EXPANDED(val))
            {
                /*
                 * we want to flatten the expanded value so that the
                 * constructed tuple doesn't depend on it
                 */
                ExpandedObjectHeader *eoh = DatumGetEOHP(datum);
 
                data = (char *) att_nominal_alignby(data, att->attalignby);
                data_length = EOH_get_flat_size(eoh);
                EOH_flatten_into(eoh, data, data_length);
            }
            else
            {
                *infomask |= HEAP_HASEXTERNAL;
                /* no alignment, since it's short by definition */
                data_length = VARSIZE_EXTERNAL(val);
                memcpy(data, val, data_length);
            }
        }
        else if (VARATT_IS_SHORT(val))
        {
            /* no alignment for short varlenas */
            data_length = VARSIZE_SHORT(val);
            memcpy(data, val, data_length);
        }
        else if (att->attispackable && VARATT_CAN_MAKE_SHORT(val))
        {
            /* convert to short varlena -- no alignment */
            data_length = VARATT_CONVERTED_SHORT_SIZE(val);
            SET_VARSIZE_SHORT(data, data_length);
            memcpy(data + 1, VARDATA(val), data_length - 1);
        }
        else
        {
            /* full 4-byte header varlena */
            data = (char *) att_nominal_alignby(data, att->attalignby);
            data_length = VARSIZE(val);
            memcpy(data, val, data_length);
        }
    }
    else if (att->attlen == -2)
    {
        /* cstring ... never needs alignment */
        *infomask |= HEAP_HASVARWIDTH;
        Assert(att->attalignby == sizeof(char));
        data_length = strlen(DatumGetCString(datum)) + 1;
        memcpy(data, DatumGetPointer(datum), data_length);
    }
    else
    {
        /* fixed-length pass-by-reference */
        data = (char *) att_nominal_alignby(data, att->attalignby);
        Assert(att->attlen > 0);
        data_length = att->attlen;
        memcpy(data, DatumGetPointer(datum), data_length);
    }
 
    data += data_length;
    *dataP = data;
}
 
/*
 * heap_fill_tuple
 *      Load data portion of a tuple from values/isnull arrays
 *
 * We also fill the null bitmap (if any) and set the infomask bits
 * that reflect the tuple's data contents.
 *
 * NOTE: it is now REQUIRED that the caller have pre-zeroed the data area.
 */
void
heap_fill_tuple(TupleDesc tupleDesc,
                const Datum *values, const bool *isnull,
                char *data, Size data_size,
                uint16 *infomask, uint8 *bit)
{
    uint8      *bitP;
    int         bitmask;
    int         i;
    int         numberOfAttributes = tupleDesc->natts;
 
#ifdef USE_ASSERT_CHECKING
    char       *start = data;
#endif
 
    if (bit != NULL)
    {
        bitP = &bit[-1];
        bitmask = HIGHBIT;
    }
    else
    {
        /* just to keep compiler quiet */
        bitP = NULL;
        bitmask = 0;
    }
 
    *infomask &= ~(HEAP_HASNULL | HEAP_HASVARWIDTH | HEAP_HASEXTERNAL);
 
    for (i = 0; i < numberOfAttributes; i++)
    {
        CompactAttribute *attr = TupleDescCompactAttr(tupleDesc, i);
 
        fill_val(attr,
                 bitP ? &bitP : NULL,
                 &bitmask,
                 &data,
                 infomask,
                 values ? values[i] : PointerGetDatum(NULL),
                 isnull ? isnull[i] : true);
    }
 
    Assert((data - start) == data_size);
}
 
 
/* ----------------------------------------------------------------
 *                      heap tuple interface
 * ----------------------------------------------------------------
 */
 
/* ----------------
 *      heap_attisnull  - returns true iff tuple attribute is not present
 * ----------------
 */
bool
heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
{
    /*
     * We allow a NULL tupledesc for relations not expected to have missing
     * values, such as catalog relations and indexes.
     */
    Assert(!tupleDesc || attnum <= tupleDesc->natts);
    if (attnum > (int) HeapTupleHeaderGetNatts(tup->t_data))
    {
        if (tupleDesc &&
            TupleDescCompactAttr(tupleDesc, attnum - 1)->atthasmissing)
            return false;
        else
            return true;
    }
 
    if (attnum > 0)
    {
        if (HeapTupleNoNulls(tup))
            return false;
        return att_isnull(attnum - 1, tup->t_data->t_bits);
    }
 
    switch (attnum)
    {
        case TableOidAttributeNumber:
        case SelfItemPointerAttributeNumber:
        case MinTransactionIdAttributeNumber:
        case MinCommandIdAttributeNumber:
        case MaxTransactionIdAttributeNumber:
        case MaxCommandIdAttributeNumber:
            /* these are never null */
            break;
 
        default:
            elog(ERROR, "invalid attnum: %d", attnum);
    }
 
    return false;
}
 
/* ----------------
 *      nocachegetattr
 *
 *      This only gets called from fastgetattr(), in cases where we
 *      can't use the attcacheoff and the value is not null.
 *
 *      NOTE: if you need to change this code, see also heap_deform_tuple.
 *      Also see nocache_index_getattr, which is the same code for index
 *      tuples.
 * ----------------
 */
Datum
nocachegetattr(HeapTuple tup,
               int attnum,
               TupleDesc tupleDesc)
{
    CompactAttribute *cattr;
    HeapTupleHeader td = tup->t_data;
    char       *tp;             /* ptr to data part of tuple */
    uint8      *bp = td->t_bits;    /* ptr to null bitmap in tuple */
    Size        off;            /* current offset within data */
    int         startAttr;
    int         firstNullAttr;
    int         i;
    bool        hasnulls = HeapTupleHasNulls(tup);
 
    /*
     * It shouldn't be possible to allocate overlength tuples, so it's not
     * possible to get in wraparound problems in the arithmetic below.
     */
    Assert(AllocSizeIsValid(tup->t_len));
 
    /* Did someone forget to call TupleDescFinalize()? */
    Assert(tupleDesc->firstNonCachedOffsetAttr >= 0);
 
    attnum--;
 
    /*
     * To minimize the number of attributes we need to look at, start walking
     * the tuple at the attribute with the highest attcacheoff prior to attnum
     * or the first NULL attribute prior to attnum, whichever comes first.
     */
    if (hasnulls)
        firstNullAttr = first_null_attr(bp, attnum);
    else
        firstNullAttr = attnum;
 
    if (tupleDesc->firstNonCachedOffsetAttr > 0 && firstNullAttr > 0)
    {
        /*
         * Try to start with the highest attribute with an attcacheoff that's
         * prior to the one we're looking for, or with the attribute prior to
         * the first NULL attribute, if there is one.
         */
        startAttr = Min(tupleDesc->firstNonCachedOffsetAttr - 1, firstNullAttr - 1);
        off = TupleDescCompactAttr(tupleDesc, startAttr)->attcacheoff;
    }
    else
    {
        /* Otherwise, start at the beginning... */
        startAttr = 0;
        off = 0;
    }
 
    tp = (char *) td + td->t_hoff;
 
    /*
     * Calculate 'off' up to the first NULL attr.  We use two cheaper loops
     * when the tuple has no variable-width columns.  When variable-width
     * columns exists, we use att_addlength_pointer() to move the offset
     * beyond the current attribute.
     */
    if (!HeapTupleHasVarWidth(tup))
    {
        for (i = startAttr; i < firstNullAttr; i++)
        {
            cattr = TupleDescCompactAttr(tupleDesc, i);
 
            off = att_nominal_alignby(off, cattr->attalignby);
            off += cattr->attlen;
        }
 
        for (; i < attnum; i++)
        {
            if (att_isnull(i, bp))
                continue;
 
            cattr = TupleDescCompactAttr(tupleDesc, i);
 
            off = att_nominal_alignby(off, cattr->attalignby);
            off += cattr->attlen;
        }
    }
    else
    {
        for (i = startAttr; i < firstNullAttr; i++)
        {
            int         attlen;
 
            cattr = TupleDescCompactAttr(tupleDesc, i);
            attlen = cattr->attlen;
            off = att_pointer_alignby(off,
                                      cattr->attalignby,
                                      attlen,
                                      tp + off);
            off = att_addlength_pointer(off, attlen, tp + off);
        }
 
        for (; i < attnum; i++)
        {
            int         attlen;
 
            if (att_isnull(i, bp))
                continue;
 
            cattr = TupleDescCompactAttr(tupleDesc, i);
            attlen = cattr->attlen;
            off = att_pointer_alignby(off, cattr->attalignby, attlen,
                                      tp + off);
            off = att_addlength_pointer(off, attlen, tp + off);
        }
    }
 
    cattr = TupleDescCompactAttr(tupleDesc, attnum);
    off = att_pointer_alignby(off,
                              cattr->attalignby,
                              cattr->attlen,
                              tp + off);
 
    return fetchatt(cattr, tp + off);
}
 
/* ----------------
 *      heap_getsysattr
 *
 *      Fetch the value of a system attribute for a tuple.
 *
 * This is a support routine for heap_getattr().  The function has already
 * determined that the attnum refers to a system attribute.
 * ----------------
 */
Datum
heap_getsysattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
{
    Datum       result;
 
    Assert(tup);
 
    /* Currently, no sys attribute ever reads as NULL. */
    *isnull = false;
 
    switch (attnum)
    {
        case SelfItemPointerAttributeNumber:
            /* pass-by-reference datatype */
            result = PointerGetDatum(&(tup->t_self));
            break;
        case MinTransactionIdAttributeNumber:
            result = TransactionIdGetDatum(HeapTupleHeaderGetRawXmin(tup->t_data));
            break;
        case MaxTransactionIdAttributeNumber:
            result = TransactionIdGetDatum(HeapTupleHeaderGetRawXmax(tup->t_data));
            break;
        case MinCommandIdAttributeNumber:
        case MaxCommandIdAttributeNumber:
 
            /*
             * cmin and cmax are now both aliases for the same field, which
             * can in fact also be a combo command id.  XXX perhaps we should
             * return the "real" cmin or cmax if possible, that is if we are
             * inside the originating transaction?
             */
            result = CommandIdGetDatum(HeapTupleHeaderGetRawCommandId(tup->t_data));
            break;
        case TableOidAttributeNumber:
            result = ObjectIdGetDatum(tup->t_tableOid);
            break;
        default:
            elog(ERROR, "invalid attnum: %d", attnum);
            result = 0;         /* keep compiler quiet */
            break;
    }
    return result;
}
 
/* ----------------
 *      heap_copytuple
 *
 *      returns a copy of an entire tuple
 *
 * The HeapTuple struct, tuple header, and tuple data are all allocated
 * as a single palloc() block.
 * ----------------
 */
HeapTuple
heap_copytuple(HeapTuple tuple)
{
    HeapTuple   newTuple;
 
    if (!HeapTupleIsValid(tuple) || tuple->t_data == NULL)
        return NULL;
 
    newTuple = (HeapTuple) palloc(HEAPTUPLESIZE + tuple->t_len);
    newTuple->t_len = tuple->t_len;
    newTuple->t_self = tuple->t_self;
    newTuple->t_tableOid = tuple->t_tableOid;
    newTuple->t_data = (HeapTupleHeader) ((char *) newTuple + HEAPTUPLESIZE);
    memcpy(newTuple->t_data, tuple->t_data, tuple->t_len);
    return newTuple;
}
 
/* ----------------
 *      heap_copytuple_with_tuple
 *
 *      copy a tuple into a caller-supplied HeapTuple management struct
 *
 * Note that after calling this function, the "dest" HeapTuple will not be
 * allocated as a single palloc() block (unlike with heap_copytuple()).
 * ----------------
 */
void
heap_copytuple_with_tuple(HeapTuple src, HeapTuple dest)
{
    if (!HeapTupleIsValid(src) || src->t_data == NULL)
    {
        dest->t_data = NULL;
        return;
    }
 
    dest->t_len = src->t_len;
    dest->t_self = src->t_self;
    dest->t_tableOid = src->t_tableOid;
    dest->t_data = (HeapTupleHeader) palloc(src->t_len);
    memcpy(dest->t_data, src->t_data, src->t_len);
}
 
/*
 * Expand a tuple which has fewer attributes than required. For each attribute
 * not present in the sourceTuple, if there is a missing value that will be
 * used. Otherwise the attribute will be set to NULL.
 *
 * The source tuple must have fewer attributes than the required number.
 *
 * Only one of targetHeapTuple and targetMinimalTuple may be supplied. The
 * other argument must be NULL.
 */
static void
expand_tuple(HeapTuple *targetHeapTuple,
             MinimalTuple *targetMinimalTuple,
             HeapTuple sourceTuple,
             TupleDesc tupleDesc)
{
    AttrMissing *attrmiss = NULL;
    int         attnum;
    int         firstmissingnum;
    bool        hasNulls = HeapTupleHasNulls(sourceTuple);
    HeapTupleHeader targetTHeader;
    HeapTupleHeader sourceTHeader = sourceTuple->t_data;
    int         sourceNatts = HeapTupleHeaderGetNatts(sourceTHeader);
    int         natts = tupleDesc->natts;
    int         sourceNullLen;
    int         targetNullLen;
    Size        sourceDataLen = sourceTuple->t_len - sourceTHeader->t_hoff;
    Size        targetDataLen;
    Size        len;
    int         hoff;
    uint8      *nullBits = NULL;
    int         bitMask = 0;
    char       *targetData;
    uint16     *infoMask;
 
    Assert((targetHeapTuple && !targetMinimalTuple)
           || (!targetHeapTuple && targetMinimalTuple));
 
    if (HeapTupleHeaderIsVersionedDatum(sourceTHeader))
        heap_datum_check(sourceTHeader, tupleDesc);
 
    Assert(sourceNatts < natts);
 
    sourceNullLen = (hasNulls ? BITMAPLEN(sourceNatts) : 0);
 
    targetDataLen = sourceDataLen;
 
    if (tupleDesc->constr &&
        tupleDesc->constr->missing)
    {
        /*
         * If there are missing values we want to put them into the tuple.
         * Before that we have to compute the extra length for the values
         * array and the variable length data.
         */
        attrmiss = tupleDesc->constr->missing;
 
        /*
         * Find the first item in attrmiss for which we don't have a value in
         * the source. We can ignore all the missing entries before that.
         */
        for (firstmissingnum = sourceNatts;
             firstmissingnum < natts;
             firstmissingnum++)
        {
            if (attrmiss[firstmissingnum].am_present)
                break;
            else
                hasNulls = true;
        }
 
        /*
         * Now walk the missing attributes. If there is a missing value make
         * space for it. Otherwise, it's going to be NULL.
         */
        for (attnum = firstmissingnum;
             attnum < natts;
             attnum++)
        {
            if (attrmiss[attnum].am_present)
            {
                CompactAttribute *att = TupleDescCompactAttr(tupleDesc, attnum);
 
                targetDataLen = att_datum_alignby(targetDataLen,
                                                  att->attalignby,
                                                  att->attlen,
                                                  attrmiss[attnum].am_value);
 
                targetDataLen = att_addlength_datum(targetDataLen,
                                                    att->attlen,
                                                    attrmiss[attnum].am_value);
 
                if (!AllocSizeIsValid(targetDataLen))
                    ereport(ERROR,
                            errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                            errmsg("tuple is too big"));
            }
            else
            {
                /* no missing value, so it must be null */
                hasNulls = true;
            }
        }
    }                           /* end if have missing values */
    else
    {
        /*
         * If there are no missing values at all then NULLS must be allowed,
         * since some of the attributes are known to be absent.
         */
        hasNulls = true;
    }
 
    len = 0;
 
    if (hasNulls)
    {
        targetNullLen = BITMAPLEN(natts);
        len += targetNullLen;
    }
    else
        targetNullLen = 0;
 
    /*
     * Allocate and zero the space needed.  Note that the tuple body and
     * HeapTupleData management structure are allocated in one chunk.
     */
    if (targetHeapTuple)
    {
        len += offsetof(HeapTupleHeaderData, t_bits);
        hoff = len = MAXALIGN(len); /* align user data safely */
        len += targetDataLen;
 
        *targetHeapTuple = (HeapTuple) palloc0(HEAPTUPLESIZE + len);
        (*targetHeapTuple)->t_data
            = targetTHeader
            = (HeapTupleHeader) ((char *) *targetHeapTuple + HEAPTUPLESIZE);
        (*targetHeapTuple)->t_len = len;
        (*targetHeapTuple)->t_tableOid = sourceTuple->t_tableOid;
        (*targetHeapTuple)->t_self = sourceTuple->t_self;
 
        targetTHeader->t_infomask = sourceTHeader->t_infomask;
        targetTHeader->t_hoff = hoff;
        HeapTupleHeaderSetNatts(targetTHeader, natts);
        /* invalidates t_ctid */
        heap_tuple_set_datum(targetTHeader, tupleDesc, len);
 
        if (targetNullLen > 0)
            nullBits = (uint8 *) ((char *) (*targetHeapTuple)->t_data
                                  + offsetof(HeapTupleHeaderData, t_bits));
        targetData = (char *) (*targetHeapTuple)->t_data + hoff;
        infoMask = &(targetTHeader->t_infomask);
    }
    else
    {
        len += SizeofMinimalTupleHeader;
        hoff = len = MAXALIGN(len); /* align user data safely */
        len += targetDataLen;
 
        *targetMinimalTuple = (MinimalTuple) palloc0(len);
        (*targetMinimalTuple)->t_len = len;
        (*targetMinimalTuple)->t_hoff = hoff + MINIMAL_TUPLE_OFFSET;
        (*targetMinimalTuple)->t_infomask = sourceTHeader->t_infomask;
        /* Same macro works for MinimalTuples */
        HeapTupleHeaderSetNatts(*targetMinimalTuple, natts);
 
        /* like HeapTupleHeaderClearDatum() */
        (*targetMinimalTuple)->t_infomask &= ~HEAP_IS_DATUM;
 
        if (targetNullLen > 0)
            nullBits = (uint8 *) ((char *) *targetMinimalTuple
                                  + offsetof(MinimalTupleData, t_bits));
        targetData = (char *) *targetMinimalTuple + hoff;
        infoMask = &((*targetMinimalTuple)->t_infomask);
    }
 
    if (targetNullLen > 0)
    {
        if (sourceNullLen > 0)
        {
            /* if bitmap pre-existed copy in - all is set */
            memcpy(nullBits,
                   ((char *) sourceTHeader)
                   + offsetof(HeapTupleHeaderData, t_bits),
                   sourceNullLen);
            nullBits += sourceNullLen - 1;
        }
        else
        {
            sourceNullLen = BITMAPLEN(sourceNatts);
            /* Set NOT NULL for all existing attributes */
            memset(nullBits, 0xff, sourceNullLen);
 
            nullBits += sourceNullLen - 1;
 
            if (sourceNatts & 0x07)
            {
                /* build the mask (inverted!) */
                bitMask = 0xff << (sourceNatts & 0x07);
                /* Voila */
                *nullBits = ~bitMask;
            }
        }
 
        bitMask = (1 << ((sourceNatts - 1) & 0x07));
    }                           /* End if have null bitmap */
 
    memcpy(targetData,
           ((char *) sourceTuple->t_data) + sourceTHeader->t_hoff,
           sourceDataLen);
 
    targetData += sourceDataLen;
 
    /* Now fill in the missing values */
    for (attnum = sourceNatts; attnum < natts; attnum++)
    {
        CompactAttribute *attr = TupleDescCompactAttr(tupleDesc, attnum);
 
        if (attrmiss && attrmiss[attnum].am_present)
        {
            fill_val(attr,
                     nullBits ? &nullBits : NULL,
                     &bitMask,
                     &targetData,
                     infoMask,
                     attrmiss[attnum].am_value,
                     false);
        }
        else
        {
            fill_val(attr,
                     &nullBits,
                     &bitMask,
                     &targetData,
                     infoMask,
                     (Datum) 0,
                     true);
        }
    }                           /* end loop over missing attributes */
}
 
/*
 * Fill in the missing values for a minimal HeapTuple
 */
MinimalTuple
minimal_expand_tuple(HeapTuple sourceTuple, TupleDesc tupleDesc)
{
    MinimalTuple minimalTuple;
 
    expand_tuple(NULL, &minimalTuple, sourceTuple, tupleDesc);
    return minimalTuple;
}
 
/*
 * Fill in the missing values for an ordinary HeapTuple
 */
HeapTuple
heap_expand_tuple(HeapTuple sourceTuple, TupleDesc tupleDesc)
{
    HeapTuple   heapTuple;
 
    expand_tuple(&heapTuple, NULL, sourceTuple, tupleDesc);
    return heapTuple;
}
 
/* ----------------
 *      heap_copy_tuple_as_datum
 *
 *      copy a tuple as a composite-type Datum
 * ----------------
 */
Datum
heap_copy_tuple_as_datum(HeapTuple tuple, TupleDesc tupleDesc)
{
    HeapTupleHeader td;
 
    /*
     * If the tuple contains any external TOAST pointers, we have to inline
     * those fields to meet the conventions for composite-type Datums.
     */
    if (HeapTupleHasExternal(tuple))
        return toast_flatten_tuple_to_datum(tuple->t_data,
                                            tuple->t_len,
                                            tupleDesc);
 
    /*
     * Fast path for easy case: just make a palloc'd copy and insert the
     * correct composite-Datum header fields (since those may not be set if
     * the given tuple came from disk, rather than from heap_form_tuple).
     */
    td = (HeapTupleHeader) palloc(tuple->t_len);
    memcpy(td, tuple->t_data, tuple->t_len);
 
    /* if wrongly marked, set the type from scratch */
    if (HeapTupleHeaderReallyIsDatum(td))
        heap_datum_update_type(td, tupleDesc);
    else
        heap_tuple_set_datum(td, tupleDesc, tuple->t_len);
 
    return PointerGetDatum(td);
}
 
/*
 * heap_form_tuple
 *      construct a tuple from the given values[] and isnull[] arrays,
 *      which are of the length indicated by tupleDescriptor->natts
 *
 * The result is allocated in the current memory context.
 */
HeapTuple
heap_form_tuple(TupleDesc tupleDescriptor,
                const Datum *values,
                const bool *isnull)
{
    HeapTuple   tuple;          /* return tuple */
    HeapTupleHeader td;         /* tuple data */
    Size        len,
                data_len;
    int         hoff;
    bool        hasnull = false;
    int         numberOfAttributes = tupleDescriptor->natts;
    int         i;
 
    if (numberOfAttributes > MaxTupleAttributeNumber)
        ereport(ERROR,
                (errcode(ERRCODE_TOO_MANY_COLUMNS),
                 errmsg("number of columns (%d) exceeds limit (%d)",
                        numberOfAttributes, MaxTupleAttributeNumber)));
 
    /*
     * Check for nulls
     */
    for (i = 0; i < numberOfAttributes; i++)
    {
        if (isnull[i])
        {
            hasnull = true;
            break;
        }
    }
 
    /*
     * Determine total space needed
     */
    len = offsetof(HeapTupleHeaderData, t_bits);
 
    if (hasnull)
        len += BITMAPLEN(numberOfAttributes);
 
    hoff = len = MAXALIGN(len); /* align user data safely */
 
    data_len = heap_compute_data_size(tupleDescriptor, values, isnull);
 
    len += data_len;
 
    /*
     * Allocate and zero the space needed.  Note that the tuple body and
     * HeapTupleData management structure are allocated in one chunk.
     */
    tuple = (HeapTuple) palloc0(HEAPTUPLESIZE + len);
    tuple->t_data = td = (HeapTupleHeader) ((char *) tuple + HEAPTUPLESIZE);
 
    /*
     * And fill in the information.  Note we fill the Datum fields even though
     * this tuple may never become a Datum.  This lets HeapTupleHeaderGetDatum
     * identify the tuple type if needed.
     */
    tuple->t_len = len;
    ItemPointerSetInvalid(&(tuple->t_self));
    tuple->t_tableOid = InvalidOid;
 
    /*
     * Mark the tuple as a datum-style tuple. This is safe even if we
     * eventually use it as a row type tuple, as e.g. inserting it into a
     * table will reset the relevant state.
     *
     * The reason we always set the datum fields is that there are a lot of
     * callers to heap_form_tuple() and the vast majority should have the
     * datum information. It's easier to call HeapTupleHeaderClearDatum() in
     * the few other cases.
     */
    HeapTupleHeaderSetNatts(td, numberOfAttributes);
    td->t_hoff = hoff;
 
    heap_tuple_set_datum(td, tupleDescriptor, len);
 
    heap_fill_tuple(tupleDescriptor,
                    values,
                    isnull,
                    (char *) td + hoff,
                    data_len,
                    &td->t_infomask,
                    (hasnull ? td->t_bits : NULL));
 
    return tuple;
}
 
/*
 * heap_modify_tuple
 *      form a new tuple from an old tuple and a set of replacement values.
 *
 * The replValues, replIsnull, and doReplace arrays must be of the length
 * indicated by tupleDesc->natts.  The new tuple is constructed using the data
 * from replValues/replIsnull at columns where doReplace is true, and using
 * the data from the old tuple at columns where doReplace is false.
 *
 * The result is allocated in the current memory context.
 */
HeapTuple
heap_modify_tuple(HeapTuple tuple,
                  TupleDesc tupleDesc,
                  const Datum *replValues,
                  const bool *replIsnull,
                  const bool *doReplace)
{
    int         numberOfAttributes = tupleDesc->natts;
    int         attoff;
    Datum      *values;
    bool       *isnull;
    HeapTuple   newTuple;
 
    /*
     * allocate and fill values and isnull arrays from either the tuple or the
     * repl information, as appropriate.
     *
     * NOTE: it's debatable whether to use heap_deform_tuple() here or just
     * heap_getattr() only the non-replaced columns.  The latter could win if
     * there are many replaced columns and few non-replaced ones. However,
     * heap_deform_tuple costs only O(N) while the heap_getattr way would cost
     * O(N^2) if there are many non-replaced columns, so it seems better to
     * err on the side of linear cost.
     */
    values = palloc_array(Datum, numberOfAttributes);
    isnull = palloc_array(bool, numberOfAttributes);
 
    heap_deform_tuple(tuple, tupleDesc, values, isnull);
 
    for (attoff = 0; attoff < numberOfAttributes; attoff++)
    {
        if (doReplace[attoff])
        {
            values[attoff] = replValues[attoff];
            isnull[attoff] = replIsnull[attoff];
        }
    }
 
    /*
     * create a new tuple from the values and isnull arrays
     */
    newTuple = heap_form_tuple(tupleDesc, values, isnull);
 
    pfree(values);
    pfree(isnull);
 
    /*
     * copy the identification info of the old tuple: t_self, t_tableOid.
     *
     * We used to also set t_data->t_ctid here, but that would invalidate the
     * version included in datum tuples. There are no known callers that need
     * t_ctid copied.
     */
    newTuple->t_self = tuple->t_self;
    newTuple->t_tableOid = tuple->t_tableOid;
 
    return newTuple;
}
 
/*
 * heap_modify_tuple_by_cols
 *      form a new tuple from an old tuple and a set of replacement values.
 *
 * This is like heap_modify_tuple, except that instead of specifying which
 * column(s) to replace by a boolean map, an array of target column numbers
 * is used.  This is often more convenient when a fixed number of columns
 * are to be replaced.  The replCols, replValues, and replIsnull arrays must
 * be of length nCols.  Target column numbers are indexed from 1.
 *
 * The result is allocated in the current memory context.
 */
HeapTuple
heap_modify_tuple_by_cols(HeapTuple tuple,
                          TupleDesc tupleDesc,
                          int nCols,
                          const int *replCols,
                          const Datum *replValues,
                          const bool *replIsnull)
{
    int         numberOfAttributes = tupleDesc->natts;
    Datum      *values;
    bool       *isnull;
    HeapTuple   newTuple;
    int         i;
 
    /*
     * allocate and fill values and isnull arrays from the tuple, then replace
     * selected columns from the input arrays.
     */
    values = palloc_array(Datum, numberOfAttributes);
    isnull = palloc_array(bool, numberOfAttributes);
 
    heap_deform_tuple(tuple, tupleDesc, values, isnull);
 
    for (i = 0; i < nCols; i++)
    {
        int         attnum = replCols[i];
 
        if (attnum <= 0 || attnum > numberOfAttributes)
            elog(ERROR, "invalid column number %d", attnum);
        values[attnum - 1] = replValues[i];
        isnull[attnum - 1] = replIsnull[i];
    }
 
    /*
     * create a new tuple from the values and isnull arrays
     */
    newTuple = heap_form_tuple(tupleDesc, values, isnull);
 
    pfree(values);
    pfree(isnull);
 
    /* see equivalent code in heap_modify_tuple() */
    newTuple->t_self = tuple->t_self;
    newTuple->t_tableOid = tuple->t_tableOid;
 
    return newTuple;
}
 
/*
 * Mark the tuple as a datum-style tuple.
 *
 * This includes setting the datum's length, typeid and version information.
 *
 * The caller already needs to have done HeapTupleHeaderSetNatts().
 *
 * Note that the caller needs to be sure that it is safe to use tupleDesc to
 * deform tup, since this function may remove information that could otherwise
 * have been used to detect unsafe deforming.
 *
 * See also src/backend/catalog/README.attver.md
 */
void
heap_tuple_set_datum(HeapTupleHeader tup, TupleDesc tupleDesc, uint32 len)
{
    HeapTupleHeaderSetDatumLength(tup, len);
    HeapTupleHeaderSetTypeId(tup, tupleDesc->tdtypeid);
    HeapTupleHeaderSetDatum(tup);
 
    if (tupleDesc->tdtypeid == RECORDOID)
    {
        /*
         * RECORDOID tuples are not protected by versioning (and do not need
         * to be).
         */
        HeapTupleHeaderSetTypMod(tup, tupleDesc->tdtypmod);
 
        /*
         * Invalidating t_ctid makes the tuple an unversioned datum, even if
         * it previously was a versioned one.
         */
        ItemPointerSetInvalid(&tup->t_ctid);
    }
    else
    {
        int         natts = HeapTupleHeaderGetNatts(tup);
        XLogRecPtr  version;
 
        /*
         * Stamp the datum with the version of the last attribute it actually
         * contains, not the version of the last attribute in the tuple desc.
         * That is important in case the tuple has fewer attributes than the
         * descriptor.
         *
         * A zero-attribute tuple contains no data to decode, so it is always
         * safe to deform; give it an explicit version of InvalidXLogRecPtr,
         * so it can be deformed if columns are added later (as the version is
         * stored in pg_attribute, a rowtype without columns has no version).
         *
         * It is never valid to have fewer attributes in the descriptor than
         * the tuple when forming a tuple, so error out in that case.
         * Hopefully unreachable.
         */
        if (natts == 0)
            version = InvalidXLogRecPtr;
        else if (natts == tupleDesc->natts)
            version = TupleDescGetVersion(tupleDesc);
        else if (natts < tupleDesc->natts)
            version = TupleDescGetAttrVersion(tupleDesc, natts);
        else
            elog(ERROR, "datum's descriptor has fewer (%d) attributes than tuple (%d)",
                 tupleDesc->natts, natts);
 
        HeapTupleHeaderSetVersion(tup, version);
    }
}
 
/*
 * Update the type of a datum tuple to the type of tupleDesc.
 *
 * If the tuple already is a versioned datum, it is verified to be compatible
 * with tupleDesc first, as relabeling it would otherwise hide a
 * mismatch.
 *
 * Additionally, if the current type and the target type differ, the types are
 * verified to be compatible (if possible).
 */
void
heap_datum_update_type(HeapTupleHeader tup, TupleDesc tupleDesc)
{
    Assert(HeapTupleHeaderReallyIsDatum(tup));
 
    heap_datum_check_coercion(tup, tupleDesc);
 
    heap_tuple_set_datum(tup, tupleDesc,
                         HeapTupleHeaderGetDatumLength(tup));
}
 
/*
 * Verify that the datum tuple "tup" can be deformed with "deformingDesc",
 * the descriptor the caller wants to use.
 *
 * "datumDesc" is the descriptor of the datum's own row type, against which
 * the datum's version has already been checked (if it is versioned).  Only
 * the attributes present in the tuple are compared, so this does not
 * establish that the two descriptors are interchangeable for other tuples.
 */
static void
verify_tupledesc_compatibility(HeapTupleHeader tup,
                               TupleDesc datumDesc, TupleDesc deformingDesc)
{
    int         datum_natts = HeapTupleHeaderGetNatts(tup);
    int         error_level =
        composite_type_mismatch == COMPOSITE_TYPE_MISMATCH_WARN ?
        WARNING : ERROR;
 
    /*
     * Should never get here with a datumDesc that has insufficient
     * attributes.
     */
    if (datumDesc->natts < datum_natts)
    {
        elog(error_level, "datum's descriptor has fewer (%d) attributes than tuple (%d)",
             datumDesc->natts, datum_natts);
        return;
    }
 
    /*
     * We sometimes may get called with a deformingDesc that has extra
     * attributes for resjunk columns. That's safe iff the tuple itself does
     * not have those columns (the expected case). But we can't accept cases
     * where the datum has more attributes than deformingDesc.
     */
    if (unlikely(deformingDesc->natts < datum_natts))
    {
        ereport(error_level,
                errcode(ERRCODE_DATATYPE_MISMATCH),
                errmsg("tuple descriptor has fewer (%d) attributes than tuple (%d)",
                       deformingDesc->natts, datum_natts));
        return;
    }
 
    /*
     * The message isn't translatable, due to the interpolated format strings.
     * That's OK, as this is just a defensive layer that shouldn't be reached.
     *
     * With composite_type_mismatch = warn, only the first mismatch is
     * reported.
     */
#define check_attribute_aspect(aspect, format) \
    if (unlikely(attr_datum->aspect != attr_deform->aspect)) \
    { \
        ereport(error_level, \
                errcode(ERRCODE_DATATYPE_MISMATCH), \
                errmsg_internal("datum attribute \"%s\" at position %d does not match deforming descriptor's %s ("format" vs "format")", \
                                NameStr(attr_datum->attname), \
                                i + 1, \
                                CppAsString(aspect), \
                                attr_datum->aspect, attr_deform->aspect) \
            ); \
        return; \
    }
 
    for (int i = 0; i < datum_natts; i++)
    {
        Form_pg_attribute attr_datum = TupleDescAttr(datumDesc, i);
        Form_pg_attribute attr_deform = TupleDescAttr(deformingDesc, i);
 
        /* don't care about the attribute's name being the same */
 
        if (unlikely(attr_datum->attisdropped != attr_deform->attisdropped))
        {
            /*
             * Targetlists can represent dropped columns as NULL::int4.  A
             * NULL attribute consumes neither bytes nor alignment, so its
             * type and storage metadata need not match for deforming to be
             * safe.
             *
             * See eval-plan-qual-dropped-column.spec for a test exercising
             * this path.
             */
            bool        isnull = (tup->t_infomask & HEAP_HASNULL) &&
                att_isnull(i, tup->t_bits);
 
            /*
             * XXX: At some point in the future we should also check that
             * attr_deform's NOT NULLness matches, due to the optimized
             * deforming slots can use for NOT NULL columns. But right now we
             * don't know if that's guaranteed here (and the constraints
             * applying to the tuple might not yet have been validated). We
             * also, at the moment, won't get here for slots with that
             * optimization. Therefore delay this for later.
             */
            if (isnull)
                continue;
        }
 
        /* Other dropped-column mismatches require explicit conversion. */
        check_attribute_aspect(attisdropped, "%u");
 
        /*
         * While, with an atttypid mismatch, the types could be binary
         * coercible, we can't know that here, and in any case, it should have
         * led to attribute mapping being used.
         */
        if (!attr_datum->attisdropped)
            check_attribute_aspect(atttypid, "%u");
        check_attribute_aspect(attlen, "%d");
        check_attribute_aspect(attalign, "%c");
 
        /*
         * If the attribute is dropped, byval does not matter. It'd generally
         * be correct to check byval regardless, but check_attrmap_match()
         * doesn't currently, so that could cause spurious errors.
         */
        if (!attr_datum->attisdropped)
        {
            /*
             * Theoretically bool could be wider than char, so I'm using %u
             * here.
             */
            check_attribute_aspect(attbyval, "%u");
        }
 
        /*
         * It does not seem necessary to compare atttypmod, attcollation, etc,
         * they are not required to match for correct deforming.
         */
    }
#undef check_attribute_aspect
}
 
/*
 * Report accessing a tuple with an incompatible tuple descriptor, due to a
 * version mismatch.  descVersion is the version the tuple was compared with,
 * see datum_attribute_version_ok().  This is out-of-line because it can be
 * reached via several paths.
 */
pg_noinline static void
heap_datum_version_mismatch_error(Oid tupTypeid, Oid descTypeid,
                                  XLogRecPtr tupVersion, XLogRecPtr descVersion)
{
    int         error_level =
        composite_type_mismatch == COMPOSITE_TYPE_MISMATCH_WARN ?
        WARNING : ERROR;
 
    /*
     * NB: We can't embed the versions in the primary message without making
     * test output unstable. Putting them into DETAIL would require the tests
     * to use \set VERBOSITY terse, which would also hide the other DETAIL and
     * CONTEXT lines that many of them benefit from. Therefore the versions
     * are only reported in the server log. That's not pretty, but ...
     */
 
    /* log details about the mismatch */
    ereport(LOG_SERVER_ONLY,
            errcode(ERRCODE_DATUM_VERSION_MISMATCH),
            errmsg("tuple descriptor for type %s (OID %u), version %X/%X is incompatible with tuple type %s (OID %u), version %X/%X",
                   format_type_be(descTypeid), descTypeid,
                   LSN_FORMAT_ARGS(descVersion),
                   format_type_be(tupTypeid), tupTypeid,
                   LSN_FORMAT_ARGS(tupVersion)));
 
    /* raise the actual error / warning */
    ereport(error_level,
            errcode(ERRCODE_DATUM_VERSION_MISMATCH),
            tupVersion < descVersion ?
            errmsg("row type of datum tuple was altered after the datum's creation")
            :
            errmsg("using outdated tuple descriptor when deforming row type"),
            errhint("See server log for additional details."));
}
 
/*
 * Check if the tuple can be safely decoded, despite a mismatch between the
 * descriptor's version and the tuple's, due to the tuple having fewer
 * attributes and that subset having a matching version.
 *
 * This can happen legitimately if the tuple has fewer attributes than the
 * descriptor, and only attributes not included in the tuple have been
 * altered.  To handle that case, we just need to compare the tuple's version
 * with the version number of attribute tupNatts in the tuple descriptor.
 *
 * *cmpVersion is set to the version the tuple was compared with, for the
 * caller to report a mismatch.
 */
static bool
datum_attribute_version_ok(TupleDesc tupleDesc, int tupNatts,
                           XLogRecPtr tupVersion, XLogRecPtr *cmpVersion)
{
    *cmpVersion = TupleDescGetVersion(tupleDesc);
 
    /* should only be called if the aggregate version does not match */
    Assert(*cmpVersion != tupVersion);
 
    /* always safe to deform no columns */
    if (tupNatts == 0)
        return true;
 
    /*
     * Iff the tuple is lacking columns in the descriptor, we can check the
     * version of the last column present.
     *
     * We do not allow cases where the tuple descriptor has fewer columns than
     * the tuple, as that indicates using a too old descriptor. It might be
     * safe to allow that in some cases, but there don't seem to be any
     * convincing cases that'd benefit.
     */
    if (tupleDesc->natts > tupNatts)
    {
        *cmpVersion = TupleDescGetAttrVersion(tupleDesc, tupNatts);
        return tupVersion == *cmpVersion;
    }
 
    return false;
}
 
/*
 * Fetch and return a pinned TupleDesc for the type/typmod combination.
 *
 * This switches to CurTransactionContext during the fetch, in case we get
 * called from within something like a tuplesort with a bump context (which
 * does not support freeing), which could be a problem during a syscache
 * miss. Because syscache misses can leak some memory, it should be a context
 * with a somewhat bounded lifetime. Using the current transaction context
 * seems like the most obvious choice.
 */
static TupleDesc
heap_datum_fetch_tupledesc(Oid tupTypeid, int32 tupTypmod)
{
    MemoryContext oldContext = MemoryContextSwitchTo(CurTransactionContext);
    TupleDesc   descForTuple = lookup_rowtype_tupdesc(tupTypeid, tupTypmod);
 
    MemoryContextSwitchTo(oldContext);
 
    return descForTuple;
}
 
/*
 * Fetch the tuple descriptor for the tuple using the tuple's typeid, check
 * that the tuple has the same version as that fetched descriptor and finally
 * verify that the callerDesc is compatible with that fetched TupleDesc.
 *
 * Normally this should not be needed, but we have a few codepaths that use
 * tuple descriptors that are verified to be compatible, with mismatching
 * typeids. In the places this function is used, we can't be sure that the
 * mismatch is harmless, so we re-verify compatibility.
 *
 * NB: This is not cheap, so it's worth making sure that this path is only
 * reached for cases with significant per-row costs.
 */
static void
heap_datum_fetch_compare_tupledesc(HeapTupleHeader tup,
                                   Oid tupTypeid, int32 tupTypmod,
                                   TupleDesc callerDesc)
{
    int         tupNatts = HeapTupleHeaderGetNatts(tup);
    TupleDesc   descForTuple = heap_datum_fetch_tupledesc(tupTypeid, tupTypmod);
    XLogRecPtr  descForTupleVersion = TupleDescGetVersion(descForTuple);
 
    /*
     * First check if the tuple descriptor we just looked up has a compatible
     * version. It's possible there have been incompatible alterations since
     * the tuple was formed.
     */
    if (HeapTupleHeaderIsVersionedDatum(tup))
    {
        XLogRecPtr  tupVersion = HeapTupleHeaderGetVersion(tup);
        XLogRecPtr  cmpVersion;
 
        if (unlikely(descForTupleVersion != tupVersion) &&
            !datum_attribute_version_ok(descForTuple, tupNatts, tupVersion,
                                        &cmpVersion))
            heap_datum_version_mismatch_error(tupTypeid, descForTuple->tdtypeid,
                                              tupVersion, cmpVersion);
    }
 
    /*
     * Now check that the caller's descriptor can decode this particular
     * tuple, including any physically NULL dropped-column placeholders.
     */
    verify_tupledesc_compatibility(tup, descForTuple, callerDesc);
 
    ReleaseTupleDesc(descForTuple);
}
 
/*
 * Try to verify that it is safe to coerce tup to have targetDesc's type.
 *
 * This will often be used when the types don't actually differ, so we try to
 * avoid unnecessary checks.
 */
static void
heap_datum_check_coercion(HeapTupleHeader tup, TupleDesc targetDesc)
{
    Oid         tupTypeid = HeapTupleHeaderGetTypeId(tup);
    int32       tupTypmod = HeapTupleHeaderGetTypMod(tup);
 
    Assert(HeapTupleHeaderIsDatum(tup));
 
    if (unlikely(composite_type_mismatch == COMPOSITE_TYPE_MISMATCH_DISABLED))
        return;
 
    /* can't check if this is wrongly marked as a datum tuple */
    if (!HeapTupleHeaderReallyIsDatum(tup))
        return;
 
    /*
     * Source tuple has an ephemeral row type, so we can't fetch the tuple's
     * desc to cross-check against.
     */
    if (tupTypeid == RECORDOID && tupTypmod == -1)
        return;
 
    if (tupTypeid != targetDesc->tdtypeid ||
        (targetDesc->tdtypeid == RECORDOID &&
         tupTypmod != targetDesc->tdtypmod))
    {
        /*
         * The tuple's type and the target type differ, cross check the tuple
         * descriptors against each other.
         */
        heap_datum_fetch_compare_tupledesc(tup, tupTypeid, tupTypmod, targetDesc);
    }
    else if (HeapTupleHeaderIsVersionedDatum(tup) &&
             TupleDescGetVersion(targetDesc) != HeapTupleHeaderGetVersion(tup))
    {
        /*
         * While the tuple's type and the target type are the same, their
         * versions differ. Make sure that's OK.
         */
        heap_datum_check(tup, targetDesc);
    }
}
 
/*
 * Check that a versioned datum tuple can be safely decoded with the
 * tupleDesc, raise an error if not.
 *
 * It is an error to call this for an unversioned datum, callers need to check
 * HeapTupleHeaderIsVersionedDatum() first.
 *
 * This function implements the attribute versioning checks described in
 * src/backend/catalog/README.attver.md.  For partially historical reasons, it
 * needs to handle some corner cases, described below.
 *
 * In addition to the versioning checks, this also, if the descriptor and the
 * tuple are for different types, tries to check that the datum's and the
 * descriptor's types are compatible.  We should work towards making such
 * mismatches errors, but until then the additional checks are helpful.
 */
void
heap_datum_check(HeapTupleHeader tup, TupleDesc tupleDesc)
{
    XLogRecPtr  descVersion = TupleDescGetVersion(tupleDesc);
    Oid         tupTypeid = HeapTupleHeaderGetTypeId(tup);
    int32       tupTypmod = HeapTupleHeaderGetTypMod(tup);
    XLogRecPtr  tupVersion;
 
    if (unlikely(composite_type_mismatch == COMPOSITE_TYPE_MISMATCH_DISABLED))
        return;
 
    /*
     * This should not be reachable, but given this is new infrastructure and
     * out-of-tree code might be doing unexpected things, it seems better to
     * verify with a runtime check than just an Assert().
     */
    if (unlikely(!HeapTupleHeaderIsVersionedDatum(tup)))
        elog(ERROR, "heap_datum_check() called on an unversioned datum");
 
    /* can't check if this is wrongly marked as a datum tuple */
    if (unlikely(!HeapTupleHeaderReallyIsDatum(tup)))
        return;
 
    tupVersion = HeapTupleHeaderGetVersion(tup);
 
    if (unlikely(tupleDesc->tdtypeid == RECORDOID))
    {
        /*
         * It's possible that we will get called with a RECORDOID tupledesc
         * but the datum has a different type, e.g. because some function just
         * updated the descriptor's type to RECORDOID.  In that case it's
         * really the caller's responsibility to have made sure that the type
         * is right. But we better make sure anyway.
         *
         * While it's not cheap, we can make sure this is safe by first
         * fetching the tuple descriptor for the tuple, verifying that its
         * version matches, and then checking that the two tuple descriptors
         * are compatible.
         *
         * The known paths reaching here involve per-row triggers, and
         * EvalPlanQual rechecks of whole-row references to function scans,
         * where the cost of the additional checking is acceptable.
         */
        heap_datum_fetch_compare_tupledesc(tup, tupTypeid, tupTypmod,
                                           tupleDesc);
    }
    else if (unlikely(tupTypeid == InvalidOid))
    {
        /*
         * This could happen if code does a heap_form_tuple() and then
         * overwrites typeid etc with invalid fields. However most such code
         * is already handled via the HeapTupleHeaderReallyIsDatum() above.
         *
         * NB: In contrast to some other paths in this function, we can't
         * fetch the tuple's "real" tuple descriptor, we lack a valid type
         * oid.
         */
        ereport(ERROR,
                errmsg_internal("datum tuple without type information"),
                errhint_internal("An extension may need to be updated."));
    }
    else if (unlikely(tupTypeid == RECORDOID))
    {
        /*
         * The tupledesc has a version number, but the tuple is a record
         * tuple, for which we do not store a version number (since it has to
         * be a blessed tupledesc that can never change and there are no
         * catalog entries to associate the version with either).
         *
         * This should not be reached, we don't mark a datum as versioned for
         * RECORDOID, but could be reached if some caller relabels a versioned
         * datum as RECORDOID without going through heap_tuple_set_datum().
         */
        elog(ERROR, "processing record datum (%u, %d) with rowtype tupdesc (%u, %d, %X/%X)",
             tupTypeid, tupTypmod,
             tupleDesc->tdtypeid, tupleDesc->tdtypmod,
             LSN_FORMAT_ARGS(descVersion));
    }
    else if (unlikely(tupleDesc->tdtypeid != tupTypeid))
    {
        /*
         * In some partitioned workloads, we currently use the parent
         * tupledesc to deform a child tuple, or vice versa. Typically the
         * caller will have verified that no conversion is necessary (c.f.
         * build_attrmap_by_name_if_req()), but we can't verify that that
         * happened here.
         *
         * XXX: This code pattern seems problematic, but it's probably not
         * feasible to fix this in the back branches. Medium term I think the
         * tuple conversion paths should update the tuple's typeid even when
         * otherwise no conversion is needed.
         *
         * To make sure this cannot lead to unsafe deforming, we check that
         * the tuple descriptor for the tuple (identified by typeid and
         * version) and the one used by the caller are compatible.
         *
         * The known cases leading here are DML with triggers and/or ON
         * CONFLICT, where the per-row cost of this check is acceptable.
         */
        heap_datum_fetch_compare_tupledesc(tup, tupTypeid, tupTypmod,
                                           tupleDesc);
    }
    else if (unlikely(tupVersion != descVersion))
    {
        XLogRecPtr  cmpVersion;
 
        /*
         * The tuple's version does not match the tuple descriptor's.
         *
         * Check if that's solely because the tuple is shorter (i.e. only new
         * columns have been added since the tuple was formed).
         *
         * Otherwise report the mismatch.
         */
        if (!datum_attribute_version_ok(tupleDesc, HeapTupleHeaderGetNatts(tup),
                                        tupVersion, &cmpVersion))
            heap_datum_version_mismatch_error(tupTypeid, tupleDesc->tdtypeid,
                                              tupVersion, cmpVersion);
    }
}
 
/*
 * Helper for DatumGetHeapTupleHeader / DatumGetHeapTupleHeaderCopy.
 *
 * This implements the "Upgrading from pre-versioning composite datums" logic
 * in src/backend/catalog/README.attver.md.
 *
 * Due to requiring a copy of the input tuple, this isn't exactly cheap, but
 * there should be fewer and fewer unversioned tuples in clusters over time, as
 * such datums get re-formed or deleted. We unfortunately can't just fix them
 * in-place without causing larger issues.
 */
static inline HeapTupleHeader
DatumGetHeapTupleHeaderImpl(Datum t, bool copy, bool *was_datum)
{
    struct varlena *tpr = (struct varlena *) DatumGetPointer(t);
    HeapTupleHeader tp;
    Oid         tupTypeid;
 
    if (copy)
        tp = (HeapTupleHeader) pg_detoast_datum_copy(tpr);
    else
    {
        tp = (HeapTupleHeader) pg_detoast_datum(tpr);
        copy = ((struct varlena *) tp) != tpr;
    }
 
    tupTypeid = HeapTupleHeaderGetTypeId(tp);
 
    if (was_datum)
        *was_datum = true;
 
    if (!HeapTupleHeaderIsDatum(tp))
    {
        Assert(HeapTupleHeaderGetDatumLength(tp) > 0);
 
        if (was_datum)
            *was_datum = false;
 
        /*
         * We need to modify the tuple header but it hasn't been copied yet
         * (not detoasted, not called by DatumGetHeapTupleHeaderCopy), copy it
         * now.
         */
        if (!copy)
        {
            Size        sz = HeapTupleHeaderGetDatumLength(tp);
            HeapTupleHeader tp2;
 
            copy = true;
 
            tp2 = (HeapTupleHeader) palloc(sz);
            memcpy(tp2, tp, sz);
            tp = tp2;
        }
 
        /*
         * Mark as a datum tuple, versioned at version InvalidXLogRecPtr
         * unless it's a RECORDOID style datum.
         */
        HeapTupleHeaderSetDatum(tp);
        if (tupTypeid != RECORDOID)
            HeapTupleHeaderSetVersion(tp, InvalidXLogRecPtr);
    }
 
    Assert(HeapTupleHeaderReallyIsDatum(tp));
 
    return tp;
}
 
HeapTupleHeader
DatumGetHeapTupleHeader(Datum t)
{
    return DatumGetHeapTupleHeaderImpl(t, false, NULL);
}
 
/*
 * Like DatumGetHeapTupleHeader but returns whether the datum was already
 * marked as a datum in *was_datum.
 */
HeapTupleHeader
DatumGetHeapTupleHeaderExt(Datum t, bool *was_datum)
{
    return DatumGetHeapTupleHeaderImpl(t, false, was_datum);
}
 
HeapTupleHeader
DatumGetHeapTupleHeaderCopy(Datum t)
{
    return DatumGetHeapTupleHeaderImpl(t, true, NULL);
}
 
/*
 * heap_deform_tuple
 *      Given a tuple, extract data into values/isnull arrays; this is
 *      the inverse of heap_form_tuple.
 *
 *      Storage for the values/isnull arrays is provided by the caller;
 *      it should be sized according to tupleDesc->natts not
 *      HeapTupleHeaderGetNatts(tuple->t_data).
 *
 *      Note that for pass-by-reference datatypes, the pointer placed
 *      in the Datum will point into the given tuple.
 *
 *      When all or most of a tuple's fields need to be extracted,
 *      this routine will be significantly quicker than a loop around
 *      heap_getattr; the loop will become O(N^2) as soon as any
 *      noncacheable attribute offsets are involved.
 */
void
heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc,
                  Datum *values, bool *isnull)
{
    HeapTupleHeader tup = tuple->t_data;
    CompactAttribute *cattr;
    bool        hasnulls = HeapTupleHasNulls(tuple);
    int         tdesc_natts = tupleDesc->natts;
    int         natts;          /* number of atts to extract */
    int         attnum;
    char       *tp;             /* ptr to tuple data */
    uint32      off;            /* offset in tuple data */
    uint8      *bp = tup->t_bits;   /* ptr to null bitmap in tuple */
    int         firstNonCacheOffsetAttr;
    int         firstNullAttr;
 
    if (HeapTupleHeaderIsVersionedDatum(tup))
        heap_datum_check(tup, tupleDesc);
 
    natts = HeapTupleHeaderGetNatts(tup);
 
    /* Did someone forget to call TupleDescFinalize()? */
    Assert(tupleDesc->firstNonCachedOffsetAttr >= 0);
 
    /*
     * In inheritance situations, it is possible that the given tuple actually
     * has more fields than the caller is expecting.  Don't run off the end of
     * the caller's arrays.
     */
    natts = Min(natts, tdesc_natts);
    firstNonCacheOffsetAttr = Min(tupleDesc->firstNonCachedOffsetAttr, natts);
 
    if (hasnulls)
    {
        firstNullAttr = first_null_attr(bp, natts);
 
        /*
         * XXX: it'd be nice to use populate_isnull_array() here, but that
         * requires that the isnull array's size is rounded up to the next
         * multiple of 8.  Doing that would require adjusting many locations
         * that allocate the array.
         */
        firstNonCacheOffsetAttr = Min(firstNonCacheOffsetAttr, firstNullAttr);
    }
    else
        firstNullAttr = natts;
 
    tp = (char *) tup + tup->t_hoff;
    attnum = 0;
 
    if (firstNonCacheOffsetAttr > 0)
    {
#ifdef USE_ASSERT_CHECKING
        /* In Assert enabled builds, verify attcacheoff is correct */
        int         offcheck = 0;
#endif
        do
        {
            isnull[attnum] = false;
            cattr = TupleDescCompactAttr(tupleDesc, attnum);
            off = cattr->attcacheoff;
 
#ifdef USE_ASSERT_CHECKING
            offcheck = att_nominal_alignby(offcheck, cattr->attalignby);
            Assert(offcheck == cattr->attcacheoff);
            offcheck += cattr->attlen;
#endif
 
            values[attnum] = fetch_att_noerr(tp + off,
                                             cattr->attbyval,
                                             cattr->attlen);
        } while (++attnum < firstNonCacheOffsetAttr);
        off += cattr->attlen;
    }
    else
        off = 0;
 
    for (; attnum < firstNullAttr; attnum++)
    {
        isnull[attnum] = false;
        cattr = TupleDescCompactAttr(tupleDesc, attnum);
        values[attnum] = align_fetch_then_add(tp,
                                              &off,
                                              cattr->attbyval,
                                              cattr->attlen,
                                              cattr->attalignby);
    }
 
    for (; attnum < natts; attnum++)
    {
        Assert(hasnulls);
 
        if (att_isnull(attnum, bp))
        {
            values[attnum] = (Datum) 0;
            isnull[attnum] = true;
            continue;
        }
 
        isnull[attnum] = false;
        cattr = TupleDescCompactAttr(tupleDesc, attnum);
 
        /* align 'off', fetch the attr's value, and increment off beyond it */
        values[attnum] = align_fetch_then_add(tp,
                                              &off,
                                              cattr->attbyval,
                                              cattr->attlen,
                                              cattr->attalignby);
    }
 
    /*
     * If tuple doesn't have all the atts indicated by tupleDesc, read the
     * rest as nulls or missing values as appropriate.
     */
    for (; attnum < tdesc_natts; attnum++)
        values[attnum] = getmissingattr(tupleDesc, attnum + 1, &isnull[attnum]);
}
 
/*
 * heap_freetuple
 */
void
heap_freetuple(HeapTuple htup)
{
    pfree(htup);
}
 
 
/*
 * heap_form_minimal_tuple
 *      construct a MinimalTuple from the given values[] and isnull[] arrays,
 *      which are of the length indicated by tupleDescriptor->natts
 *
 * This is exactly like heap_form_tuple() except that the result is a
 * "minimal" tuple lacking a HeapTupleData header as well as room for system
 * columns.
 *
 * The result is allocated in the current memory context.
 */
MinimalTuple
heap_form_minimal_tuple(TupleDesc tupleDescriptor,
                        const Datum *values,
                        const bool *isnull,
                        Size extra)
{
    MinimalTuple tuple;         /* return tuple */
    char       *mem;
    Size        len,
                data_len;
    int         hoff;
    bool        hasnull = false;
    int         numberOfAttributes = tupleDescriptor->natts;
    int         i;
 
    Assert(extra == MAXALIGN(extra));
 
    if (numberOfAttributes > MaxTupleAttributeNumber)
        ereport(ERROR,
                (errcode(ERRCODE_TOO_MANY_COLUMNS),
                 errmsg("number of columns (%d) exceeds limit (%d)",
                        numberOfAttributes, MaxTupleAttributeNumber)));
 
    /*
     * Check for nulls
     */
    for (i = 0; i < numberOfAttributes; i++)
    {
        if (isnull[i])
        {
            hasnull = true;
            break;
        }
    }
 
    /*
     * Determine total space needed
     */
    len = SizeofMinimalTupleHeader;
 
    if (hasnull)
        len += BITMAPLEN(numberOfAttributes);
 
    hoff = len = MAXALIGN(len); /* align user data safely */
 
    data_len = heap_compute_data_size(tupleDescriptor, values, isnull);
 
    len += data_len;
 
    /*
     * Allocate and zero the space needed.
     */
    mem = palloc0(len + extra);
    tuple = (MinimalTuple) (mem + extra);
 
    /*
     * And fill in the information.
     */
    tuple->t_len = len;
    HeapTupleHeaderSetNatts(tuple, numberOfAttributes);
    tuple->t_hoff = hoff + MINIMAL_TUPLE_OFFSET;
 
    heap_fill_tuple(tupleDescriptor,
                    values,
                    isnull,
                    (char *) tuple + hoff,
                    data_len,
                    &tuple->t_infomask,
                    (hasnull ? tuple->t_bits : NULL));
 
    return tuple;
}
 
/*
 * heap_free_minimal_tuple
 */
void
heap_free_minimal_tuple(MinimalTuple mtup)
{
    pfree(mtup);
}
 
/*
 * heap_copy_minimal_tuple
 *      copy a MinimalTuple
 *
 * The result is allocated in the current memory context.
 */
MinimalTuple
heap_copy_minimal_tuple(MinimalTuple mtup, Size extra)
{
    MinimalTuple result;
    char       *mem;
 
    Assert(extra == MAXALIGN(extra));
    mem = palloc(mtup->t_len + extra);
    memset(mem, 0, extra);
    result = (MinimalTuple) (mem + extra);
    memcpy(result, mtup, mtup->t_len);
    return result;
}
 
/*
 * heap_tuple_from_minimal_tuple
 *      create a HeapTuple by copying from a MinimalTuple;
 *      system columns are filled with zeroes
 *
 * The result is allocated in the current memory context.
 * The HeapTuple struct, tuple header, and tuple data are all allocated
 * as a single palloc() block.
 */
HeapTuple
heap_tuple_from_minimal_tuple(MinimalTuple mtup)
{
    HeapTuple   result;
    uint32      len = mtup->t_len + MINIMAL_TUPLE_OFFSET;
 
    result = (HeapTuple) palloc(HEAPTUPLESIZE + len);
    result->t_len = len;
    ItemPointerSetInvalid(&(result->t_self));
    result->t_tableOid = InvalidOid;
    result->t_data = (HeapTupleHeader) ((char *) result + HEAPTUPLESIZE);
    memcpy((char *) result->t_data + MINIMAL_TUPLE_OFFSET, mtup, mtup->t_len);
    memset(result->t_data, 0, offsetof(HeapTupleHeaderData, t_infomask2));
    return result;
}
 
/*
 * minimal_tuple_from_heap_tuple
 *      create a MinimalTuple by copying from a HeapTuple
 *
 * The result is allocated in the current memory context.
 */
MinimalTuple
minimal_tuple_from_heap_tuple(HeapTuple htup, Size extra)
{
    MinimalTuple result;
    char       *mem;
    uint32      len;
 
    Assert(extra == MAXALIGN(extra));
    Assert(htup->t_len > MINIMAL_TUPLE_OFFSET);
    len = htup->t_len - MINIMAL_TUPLE_OFFSET;
    mem = palloc(len + extra);
    memset(mem, 0, extra);
    result = (MinimalTuple) (mem + extra);
    memcpy(result, (char *) htup->t_data + MINIMAL_TUPLE_OFFSET, len);
 
    /*
     * A minimal tuple won't have the necessary fields to be treated as a
     * datum tuple, so we better reset those fields lest they trigger assert
     * failures at a later point.
     *
     * XXX: It'd be good to call heap_datum_check() before losing the ability
     * to do so, but we don't have the tupledesc, so we can't trivially do so.
     * We could try to fetch the tupledesc from typeid and verify that way?
     * But that's not cheap.
     */
    if (HeapTupleHeaderIsDatum(htup->t_data))
    {
        /* like HeapTupleHeaderClearDatum() */
        result->t_infomask &= ~HEAP_IS_DATUM;
    }
 
    result->t_len = len;
    return result;
}
 
/*
 * This mainly exists so JIT can inline the definition, but it's also
 * sometimes useful in debugging sessions.
 */
size_t
varsize_any(void *p)
{
    return VARSIZE_ANY(p);
}