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
|
/*-------------------------------------------------------------------------
*
* pgtt.c
* Add support to Oracle-style Global Temporary Table in PostgreSQL.
*
* Author: Gilles Darold <gilles@darold.net>
* Licence: PostgreSQL
* Copyright (c) 2018-2025, Gilles Darold,
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <unistd.h>
#include "funcapi.h"
#include "libpq/pqformat.h"
#include "miscadmin.h"
#include "access/htup_details.h"
#include "access/parallel.h"
#include "access/reloptions.h"
#include "access/sysattr.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_database.h"
#include "catalog/pg_extension.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_type.h"
#include "catalog/toasting.h"
#include "commands/dbcommands.h"
#include "commands/defrem.h"
#include "commands/extension.h"
#include "commands/tablecmds.h"
#include "commands/comment.h"
#include "executor/spi.h"
#include "nodes/makefuncs.h"
#include "nodes/nodes.h"
#include "nodes/pg_list.h"
#include "nodes/print.h"
#include "nodes/value.h"
#include "optimizer/paths.h"
#include "optimizer/plancat.h"
#include "parser/analyze.h"
#include "parser/parse_utilcmd.h"
#include "storage/ipc.h"
#include "storage/lmgr.h"
#include "storage/proc.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/formatting.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#if PG_VERSION_NUM < 110000
#include "utils/memutils.h"
#endif
/* for regexp search */
#include "regex/regexport.h"
#if (PG_VERSION_NUM >= 120000)
#include "access/genam.h"
#include "access/heapam.h"
#include "catalog/pg_class.h"
#endif
#if PG_VERSION_NUM < 120000
#error Minimum version of PostgreSQL required is 12
#endif
#define CATALOG_GLOBAL_TEMP_REL "pg_global_temp_tables"
#define Anum_pgtt_relid 1
#define Anum_pgtt_relname 3
PG_MODULE_MAGIC;
#define NOT_IN_PARALLEL_WORKER (ParallelWorkerNumber < 0)
#if PG_VERSION_NUM >= 140000
#define STMT_OBJTYPE(stmt) stmt->objtype
#else
#define STMT_OBJTYPE(stmt) stmt->relkind
#endif
/* Define ProcessUtility hook proto/parameters following the PostgreSQL version */
#if PG_VERSION_NUM >= 140000
#define GTT_PROCESSUTILITY_PROTO PlannedStmt *pstmt, const char *queryString, \
bool readOnlyTree, \
ProcessUtilityContext context, ParamListInfo params, \
QueryEnvironment *queryEnv, DestReceiver *dest, \
QueryCompletion *qc
#define GTT_PROCESSUTILITY_ARGS pstmt, queryString, readOnlyTree, context, params, queryEnv, dest, qc
#else
#if PG_VERSION_NUM >= 130000
#define GTT_PROCESSUTILITY_PROTO PlannedStmt *pstmt, const char *queryString, \
ProcessUtilityContext context, ParamListInfo params, \
QueryEnvironment *queryEnv, DestReceiver *dest, \
QueryCompletion *qc
#define GTT_PROCESSUTILITY_ARGS pstmt, queryString, context, params, queryEnv, dest, qc
#else
#if PG_VERSION_NUM >= 100000
#define GTT_PROCESSUTILITY_PROTO PlannedStmt *pstmt, const char *queryString, \
ProcessUtilityContext context, ParamListInfo params, \
QueryEnvironment *queryEnv, DestReceiver *dest, \
char *completionTag
#define GTT_PROCESSUTILITY_ARGS pstmt, queryString, context, params, queryEnv, dest, completionTag
#elif PG_VERSION_NUM >= 90300
#define GTT_PROCESSUTILITY_PROTO Node *parsetree, const char *queryString, \
ProcessUtilityContext context, ParamListInfo params, \
DestReceiver *dest, char *completionTag
#define GTT_PROCESSUTILITY_ARGS parsetree, queryString, context, params, dest, completionTag
#else
#define GTT_PROCESSUTILITY_PROTO Node *parsetree, const char *queryString, \
ParamListInfo params, bool isTopLevel, \
DestReceiver *dest, char *completionTag
#define GTT_PROCESSUTILITY_ARGS parsetree, queryString, params, isTopLevel, dest, completionTag
#endif
#endif
#endif
/* Saved hook values in case of unload */
static ProcessUtility_hook_type prev_ProcessUtility = NULL;
static ExecutorStart_hook_type prev_ExecutorStart = NULL;
static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
/* Hook to intercept CREATE GLOBAL TEMPORARY TABLE query */
static void gtt_ProcessUtility(GTT_PROCESSUTILITY_PROTO);
static void gtt_ExecutorStart(QueryDesc *queryDesc, int eflags);
#if PG_VERSION_NUM >= 140000
static void gtt_post_parse_analyze(ParseState *pstate, Query *query, struct JumbleState * jstate);
#else
static void gtt_post_parse_analyze(ParseState *pstate, Query *query);
#endif
static void gtt_try_load(void);
#if PG_VERSION_NUM < 160000
Oid get_extension_schema(Oid ext_oid);
#endif
static bool is_declared_gtt(Oid relid);
/* Enable use of Global Temporary Table at session level */
bool pgtt_is_enabled = true;
/* Regular expression search */
#define CREATE_GLOBAL_REGEXP "^\\s*CREATE\\s+(?:\\/\\*\\s*)?GLOBAL(?:\\s*\\*\\/)?"
#define CREATE_WITH_FK_REGEXP "\\s*FOREIGN\\s+KEY"
/* Oid and name of pgtt extrension schema in the database */
Oid pgtt_namespace_oid = InvalidOid;
char pgtt_namespace_name[NAMEDATALEN];
/* In memory storage of GTT and state */
typedef struct Gtt
{
Oid relid;
Oid temp_relid;
char relname[NAMEDATALEN];
bool preserved;
bool created;
char *code;
} Gtt;
typedef struct relhashent
{
char name[NAMEDATALEN];
Gtt gtt;
} GttHashEnt;
static HTAB *GttHashTable = NULL;
/* Default size of the storage area for GTT but will be dynamically extended */
#define GTT_PER_DATABASE 16
#define GttHashTableDelete(NAME) \
do { \
GttHashEnt *hentry; \
\
hentry = (GttHashEnt *) hash_search(GttHashTable, NAME, HASH_REMOVE, NULL); \
if (hentry == NULL) \
elog(DEBUG1, "trying to delete GTT entry in HTAB that does not exist"); \
} while(0)
#define GttHashTableLookup(NAME, GTT) \
do { \
GttHashEnt *hentry; \
\
hentry = (GttHashEnt *) hash_search(GttHashTable, \
(NAME), HASH_FIND, NULL); \
if (hentry) \
GTT = hentry->gtt; \
} while(0)
#define GttHashTableInsert(GTT, NAME) \
do { \
GttHashEnt *hentry; bool found; \
\
hentry = (GttHashEnt *) hash_search(GttHashTable, \
(NAME), HASH_ENTER, &found); \
if (found) \
elog(ERROR, "duplicate GTT name"); \
hentry->gtt = GTT; \
strcpy(hentry->name, NAME); \
elog(DEBUG1, "Insert GTT entry in HTAB, key: %s, relid: %d, temp_relid: %d, created: %d", hentry->gtt.relname, hentry->gtt.relid, hentry->gtt.temp_relid, hentry->gtt.created); \
} while(0)
/* Function declarations */
PGDLLEXPORT void _PG_init(void);
PGDLLEXPORT void _PG_fini(void);
int strpos(char *hay, char *needle, int offset);
static Oid gtt_create_table_statement(Gtt gtt);
static void gtt_create_table_as(Gtt gtt, bool skipdata);
static void gtt_unregister_global_temporary_table(Oid relid, const char *relname);
void GttHashTableDeleteAll(void);
bool EnableGttManager(void);
Gtt GetGttByName(const char *name);
static void gtt_load_global_temporary_tables(void);
static Oid create_temporary_table_internal(Oid parent_relid, bool preserved);
static bool gtt_check_command(GTT_PROCESSUTILITY_PROTO);
static bool gtt_table_exists(QueryDesc *queryDesc);
void exitHook(int code, Datum arg);
static bool is_catalog_relid(Oid relid);
static void force_pgtt_namespace (void);
static void gtt_update_registered_table(Gtt gtt);
int strremovestr(char *src, char *toremove);
static void gtt_unregister_gtt_not_cached(const char *relname);
/*
* Module load callback
*/
void
_PG_init(void)
{
elog(DEBUG1, "_PG_init()");
if (ParallelWorkerNumber >= 0)
return;
/*
* If we are loaded via shared_preload_libraries exit.
*/
if (process_shared_preload_libraries_in_progress)
{
ereport(FATAL,
(errmsg("The pgtt extension can not be loaded using shared_preload_libraries."),
errhint("Add 'pgtt' to session_preload_libraries globally, or"
" for the wanted roles or databases instead.")));
}
/*
* Define (or redefine) custom GUC variables.
* No custom GUC variable at this time
*/
DefineCustomBoolVariable("pgtt.enabled",
"Enable use of Global Temporary Table",
"By default the extension is automatically enabled after load, "
"it can be temporary disable by setting the GUC value to false "
"then enable again later wnen necessary.",
&pgtt_is_enabled,
true,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
/*
* Immediately try to load the extension. This will probably be a no-op in
* the recommended "session_preload_libraries = 'pgtt'" configuration, as
* it will happen outside of a transaction, but if the extension is
* explicitly loaded with a plain LOAD command then the search_path would
* only be changed after the next command is executed. It means that the
* very first query executed after such a LOAD wouldn't see the global
* temporary tables.
*/
gtt_try_load();
/*
* Install hooks.
*/
prev_ExecutorStart = ExecutorStart_hook;
ExecutorStart_hook = gtt_ExecutorStart;
prev_post_parse_analyze_hook = post_parse_analyze_hook;
post_parse_analyze_hook = gtt_post_parse_analyze;
prev_ProcessUtility = ProcessUtility_hook;
ProcessUtility_hook = gtt_ProcessUtility;
/* set the exit hook */
on_proc_exit(&exitHook, PointerGetDatum(NULL));
}
/*
* Module unload callback
*/
void
_PG_fini(void)
{
elog(DEBUG1, "_PG_fini()");
/* Uninstall hooks. */
ExecutorStart_hook = prev_ExecutorStart;
post_parse_analyze_hook = prev_post_parse_analyze_hook;
ProcessUtility_hook = prev_ProcessUtility;
}
/*
* Exit hook.
*/
void
exitHook(int code, Datum arg)
{
elog(DEBUG1, "exiting with %d", code);
}
static void
gtt_ProcessUtility(GTT_PROCESSUTILITY_PROTO)
{
elog(DEBUG1, "gtt_ProcessUtility()");
/* Do not waste time here if the feature is not enabled for this session */
if (pgtt_is_enabled && NOT_IN_PARALLEL_WORKER)
{
/* Try to load pgtt if not already done. */
gtt_try_load();
/*
* Be sure that extension schema is at end of the search path so that
* "template" tables will be find.
*/
force_pgtt_namespace();
/*
* Check if we have a CREATE GLOBAL TEMPORARY TABLE
* in this case do more work than the simple table
* creation see SQL file in sql/ subdirectory.
*
* If the current query use a GTT that is not already
* created create it.
*/
if (gtt_check_command(GTT_PROCESSUTILITY_ARGS))
{
elog(DEBUG1, "Work on GTT from Utility Hook done, get out of UtilityHook immediately.");
return;
}
}
elog(DEBUG1, "restore ProcessUtility");
/* Excecute the utility command, we are not concerned */
PG_TRY();
{
if (prev_ProcessUtility)
prev_ProcessUtility(GTT_PROCESSUTILITY_ARGS);
else
standard_ProcessUtility(GTT_PROCESSUTILITY_ARGS);
}
PG_CATCH();
{
PG_RE_THROW();
}
PG_END_TRY();
elog(DEBUG1, "End of gtt_ProcessUtility()");
}
/*
* Look at utility command to search CREATE TABLE / DROP TABLE
* and INSERT INTO statements to see if a Global Temporary Table
* is concerned.
* Return true if all work is done and the origin statement must
* be forgotten. False mean that the statement must be processed
* normally.
*/
static bool
gtt_check_command(GTT_PROCESSUTILITY_PROTO)
{
bool preserved = true;
bool work_completed = false;
char *name = NULL;
#if PG_VERSION_NUM >= 100000
Node *parsetree = pstmt->utilityStmt;
#endif
Assert(parsetree != NULL);
Assert(queryString != NULL);
elog(DEBUG1, "gtt_check_command() on query: \"%s\"", queryString);
if (GttHashTable == NULL)
return false;
/* Intercept CREATE / DROP TABLE statements */
switch (nodeTag(parsetree))
{
case T_VariableSetStmt:
{
VariableSetStmt *stmt = (VariableSetStmt *) parsetree;
/*
* Forcing search_path is not enough because it does not
* handle SET search_path TO ... statement. This code also
* add the PGTT schema if not present in the path
*/
if (stmt->kind == VAR_SET_VALUE &&
strcmp(stmt->name, "search_path") == 0)
{
ListCell *l;
bool found = false;
if (stmt->args == NIL)
break;
foreach(l, stmt->args)
{
Node *arg = (Node *) lfirst(l);
A_Const *con = (A_Const *) arg;
char *val;
val = strVal(&con->val);
if (strcmp(val,
get_namespace_name(pgtt_namespace_oid)) == 0)
found = true;
}
/* append the extension schema to the arg list. */
if (!found)
{
A_Const *newcon = makeNode(A_Const);
char *str = (char *) get_namespace_name(pgtt_namespace_oid);
#if PG_VERSION_NUM < 150000
newcon->val.type = T_String;
newcon->val.val.str = pstrdup(str);
#else
newcon->val.node.type = T_String;
newcon->val.sval.sval = pstrdup(str);
#endif
newcon->location = strlen(queryString);
stmt->args = lappend(stmt->args, newcon);
}
}
}
break;
case T_CreateTableAsStmt:
{
Gtt gtt;
int i;
CreateTableAsStmt *stmt = (CreateTableAsStmt *)parsetree;
bool skipdata = stmt->into->skipData;
bool regexec_result;
/* Get the name of the relation */
name = stmt->into->rel->relname;
/*
* CREATE TABLE AS is similar as SELECT INTO,
* so avoid going further in this last case.
*/
if (stmt->is_select_into)
break;
/* do not proceed OBJECT_MATVIEW */
if (STMT_OBJTYPE(stmt) != OBJECT_TABLE)
break;
/*
* Be sure to have CREATE TEMPORARY TABLE definition
*/
if (stmt->into->rel->relpersistence != RELPERSISTENCE_TEMP)
break;
/*
* We only take care here of statements with the GLOBAL keyword
* even if it is deprecated and generate a warning.
*/
regexec_result = RE_compile_and_execute(
cstring_to_text(CREATE_GLOBAL_REGEXP),
VARDATA_ANY(cstring_to_text((char *) queryString)),
VARSIZE_ANY_EXHDR(cstring_to_text((char *) queryString)),
REG_ADVANCED | REG_ICASE | REG_NEWLINE,
DEFAULT_COLLATION_OID,
0, NULL);
if (!regexec_result)
break;
/*
* What to do at commit time for global temporary relations
* default is ON COMMIT PRESERVE ROWS (do nothing)
*/
if (stmt->into->onCommit == ONCOMMIT_DELETE_ROWS)
preserved = false;
/*
* Case of ON COMMIT DROP and GLOBAL TEMPORARY might not be
* allowed, this is the same as using a normal temporary table
* inside a transaction. Here the table should be dropped after
* commit so it will not survive a transaction.
* Throw an error to prevent the use of this clause.
*/
if (stmt->into->onCommit == ONCOMMIT_DROP)
ereport(ERROR,
(errmsg("use of ON COMMIT DROP with GLOBAL TEMPORARY is not allowed"),
errhint("Create a local temporary table inside a transaction instead, this is the default behavior.")));
elog(DEBUG1, "Create table %s, rows persistance: %d, GLOBAL at position: %d",
name, preserved,
strpos(asc_toupper(queryString, strlen(queryString)), "GLOBAL", 0));
/* Force creation of the temporary table in our pgtt schema */
stmt->into->rel->schemaname = pstrdup(pgtt_namespace_name);
/* replace temporary state from the table to unlogged table */
stmt->into->rel->relpersistence = RELPERSISTENCE_UNLOGGED;
/* Do not copy data in the unlogged table */
stmt->into->skipData = true;
/*
* At this stage the unlogged table will be created with normal
* utility hook. What we need now is to register the table in
* the pgtt catalog table and create a normal temporary table
* using the original statement without the GLOBAL keyword
*/
gtt.relid = 0;
gtt.temp_relid = 0;
strcpy(gtt.relname, name);
gtt.relname[strlen(name)] = 0;
gtt.preserved = preserved;
gtt.created = false;
/* Extract the AS ... code part from the query */
gtt.code = pstrdup(queryString);
for (i = 30; i < strlen(queryString) - 1; i++)
{
if ( isspace(queryString[i])
&& (queryString[i+1] == 'A' || queryString[i+1] == 'a')
&& (queryString[i+2] == 'S' || queryString[i+2] == 's')
&& (isspace(queryString[i+3]) || queryString[i+3] == '(') )
break;
}
if (i == strlen(queryString) - 1)
elog(ERROR, "can not find AS keyword in this CREATE TABLE AS statement.");
gtt.code += i;
if (gtt.code[strlen(gtt.code) - 1] == ';')
gtt.code[strlen(gtt.code) - 1] = 0;
/* remove WITH DATA from the code */
strremovestr(gtt.code, "WITH DATA");
/* Create the necessary object to emulate the GTT */
gtt_create_table_as(gtt, skipdata);
work_completed = true;
break;
}
case T_CreateStmt:
{
/* CREATE TABLE statement */
CreateStmt *stmt = (CreateStmt *)parsetree;
Gtt gtt;
int len, i, start = 0, end = 0;
bool regexec_result;
/* Get the name of the relation */
name = stmt->relation->relname;
/*
* Be sure to have CREATE TEMPORARY TABLE definition
*/
if (stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
break;
/*
* We only take care here of statements with the GLOBAL keyword
* even if it is deprecated and generate a warning.
*/
regexec_result = RE_compile_and_execute(
cstring_to_text(CREATE_GLOBAL_REGEXP),
VARDATA_ANY(cstring_to_text((char *) queryString)),
VARSIZE_ANY_EXHDR(cstring_to_text((char *) queryString)),
REG_ADVANCED | REG_ICASE | REG_NEWLINE,
DEFAULT_COLLATION_OID,
0, NULL);
if (!regexec_result)
break;
/* Check if there is foreign key defined in the statement */
regexec_result = RE_compile_and_execute(
cstring_to_text(CREATE_WITH_FK_REGEXP),
VARDATA_ANY(cstring_to_text((char *) queryString)),
VARSIZE_ANY_EXHDR(cstring_to_text((char *) queryString)),
REG_ADVANCED | REG_ICASE | REG_NEWLINE,
DEFAULT_COLLATION_OID,
0, NULL);
if (regexec_result)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("attempt to create referential integrity constraint on global temporary table")));
#if (PG_VERSION_NUM >= 100000)
/*
* We do not allow partitioning on GTT, not that PostgreSQL can
* not do it but because we want to mimic the Oracle or other
* RDBMS behavior.
*/
if (stmt->partspec != NULL)
elog(ERROR, "Global Temporary Table do not support partitioning.");
#endif
/*
* What to do at commit time for global temporary relations
* default is ON COMMIT PRESERVE ROWS (do nothing)
*/
if (stmt->oncommit == ONCOMMIT_DELETE_ROWS)
preserved = false;
/*
* Case of ON COMMIT DROP and GLOBAL TEMPORARY might not be
* allowed, this is the same as using a normal temporary table
* inside a transaction. Here the table should be dropped after
* commit so it will not survive a transaction.
* Throw an error to prevent the use of this clause.
*/
if (stmt->oncommit == ONCOMMIT_DROP)
ereport(ERROR,
(errmsg("use of ON COMMIT DROP with GLOBAL TEMPORARY is not allowed"),
errhint("Create a local temporary table inside a transaction instead, this is the default behavior.")));
elog(DEBUG1, "Create table %s, rows persistance: %d, GLOBAL at position: %d",
name, preserved,
strpos(asc_toupper(queryString, strlen(queryString)), "GLOBAL", 0));
/* Create the Global Temporary Table template and register the table */
gtt.relid = 0;
gtt.temp_relid = 0;
strcpy(gtt.relname, name);
gtt.relname[strlen(name)] = 0;
gtt.preserved = preserved;
gtt.created = false;
gtt.code = NULL;
/* Extract the definition of the table */
for (i = 0; i < strlen(queryString); i++)
{
if (queryString[i] == '(')
{
start = i;
break;
}
}
start++;
for (i = start; i < strlen(queryString); i++)
{
if (queryString[i] == ')')
{
end = i;
}
}
len = end - start;
if (end > 0 && start > 0)
{
gtt.code = palloc0(sizeof(char *) * (len + 1));
strncpy(gtt.code, queryString+start, len);
gtt.code[len] = '\0';
}
elog(DEBUG1, "code for Global Temporary Table \"%s\" creation is \"%s\"", gtt.relname, gtt.code);
/* Create the necessary object to emulate the GTT */
gtt.relid = gtt_create_table_statement(gtt);
/*
* In case of problem during GTT creation previous function
* call throw an error so the code that's follow is safe.
* Update GTT cache with table flagged as created
*/
gtt.created = false;
GttHashTableDelete(gtt.relname);
GttHashTableInsert(gtt, gtt.relname);
work_completed = true;
elog(DEBUG1, "Global Temporary Table \"%s\" created", gtt.relname);
break;
}
case T_DropStmt:
{
DropStmt *drop = (DropStmt *) parsetree;
if (drop->removeType == OBJECT_TABLE)
{
List *relationNameList = NULL;
int relationNameListLength = 0;
#if PG_VERSION_NUM < 150000
Value *relationSchemaNameValue = NULL;
Value *relationNameValue = NULL;
#else
String *relationSchemaNameValue = NULL;
String *relationNameValue = NULL;
#endif
Gtt gtt;
relationNameList = list_copy((List *) linitial(drop->objects));
relationNameListLength = list_length(relationNameList);
switch (relationNameListLength)
{
case 1:
{
relationNameValue = linitial(relationNameList);
break;
}
case 2:
{
relationSchemaNameValue = linitial(relationNameList);
relationNameValue = lsecond(relationNameList);
break;
}
case 3:
{
relationSchemaNameValue = lsecond(relationNameList);
relationNameValue = lthird(relationNameList);
break;
}
default:
{
ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("improper relation name: \"%s\"",
NameListToString(relationNameList))));
break;
}
}
/* prefix with schema name if it is not added already */
if (relationSchemaNameValue == NULL)
{
#if PG_VERSION_NUM < 150000
Value *schemaNameValue = makeString(pgtt_namespace_name);
#else
String *schemaNameValue = makeString(pgtt_namespace_name);
#endif
relationNameList = lcons(schemaNameValue, relationNameList);
}
/*
* Check if the table is in the hash list, drop
* it if it has already been be created and remove
* the cache entry.
*/
#if PG_VERSION_NUM < 150000
if (PointerIsValid(relationNameValue->val.str))
#else
if (PointerIsValid(relationNameValue->sval))
#endif
{
#if PG_VERSION_NUM < 150000
elog(DEBUG1, "looking for dropping table: %s", relationNameValue->val.str);
#else
elog(DEBUG1, "looking for dropping table: %s", relationNameValue->sval);
#endif
/* Initialize Gtt object */
gtt.relid = 0;
gtt.temp_relid = 0;
gtt.relname[0] = '\0';
gtt.preserved = false;
gtt.code = NULL;
gtt.created = false;
#if PG_VERSION_NUM < 150000
elog(DEBUG1, "looking if table %s is a cached GTT", relationNameValue->val.str);
GttHashTableLookup(relationNameValue->val.str, gtt);
#else
elog(DEBUG1, "looking if table %s is a cached GTT", relationNameValue->sval);
GttHashTableLookup(relationNameValue->sval, gtt);
#endif
if (gtt.relname[0] != '\0')
{
/*
* When the temporary table have been created
* we can not remove the GTT in the same session.
* Creating and dropping GTT can only be performed
* by a superuser in a "maintenance" session.
*/
if (gtt.created)
elog(ERROR, "can not drop a GTT that is in use.");
/*
* Unregister the Global Temporary Table and its link to the
* view stored in pg_global_temp_tables table
*/
gtt_unregister_global_temporary_table(gtt.relid, gtt.relname);
/* Remove the table from the hash table */
GttHashTableDelete(gtt.relname);
}
else
{
/*
* Table is not on current session cache but remove
* it from PGTT list if it exists.
*/
#if PG_VERSION_NUM < 150000
elog(DEBUG1, "looking if table %s is registered as GTT", relationNameValue->val.str);
gtt_unregister_gtt_not_cached(relationNameValue->val.str);
#else
elog(DEBUG1, "looking if table %s is registered as GTT", relationNameValue->sval);
gtt_unregister_gtt_not_cached(relationNameValue->sval);
#endif
}
}
}
break;
}
case T_RenameStmt:
{
/* CREATE TABLE statement */
RenameStmt *stmt = (RenameStmt *)parsetree;
Gtt gtt;
/* We only take care of tabe renaming to update our internal storage */
if (stmt->renameType != OBJECT_TABLE || stmt->newname == NULL)
break;
gtt.relid = 0;
/* Look if the table is declared as GTT */
GttHashTableLookup(stmt->relation->relname, gtt);
/* Not registered as a GTT, nothing to do here */
if (gtt.relid == 0)
break;
/* If a temporary table have already created do not allow changing name */
if (gtt.created)
elog(ERROR, "a temporary table has been created and is active, can not rename the GTT table in this session.");
/* Rename the table and get the resulting new Oid */
RenameRelation(stmt);
elog(DEBUG1, "updating registered table in %s.pg_global_temp_tables.", pgtt_namespace_name);
strcpy(gtt.relname, stmt->newname);
gtt_update_registered_table(gtt);
/* Delete and recreate the table in cache */
GttHashTableDelete(stmt->relation->relname);
GttHashTableInsert(gtt, stmt->newname);
work_completed = true;
break;
}
case T_CommentStmt:
{
/* COMMENT ON TABLE/COLUMN statement */
CommentStmt *stmt = (CommentStmt *)parsetree;
Relation relation;
char *nspname;
/* We only take care of comment on table or column to update our internal storage */
if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_COLUMN)
break;
/*
* Get the relation object by calling get_object_address().
* get_object_address() will throw an error if the object
* does not exist, and will also acquire a lock on the target
* to guard against concurrent DROP operations.
*/
#if (PG_VERSION_NUM < 100000)
(void) get_object_address(stmt->objtype, stmt->objname, stmt->objargs,
&relation, ShareUpdateExclusiveLock, false);
#else
(void) get_object_address(stmt->objtype, stmt->object,
&relation, ShareUpdateExclusiveLock, false);
#endif
/* Just take care that the GTT is not in use */
nspname = get_namespace_name(RelationGetNamespace(relation));
relation_close(relation, NoLock);
if (strcmp(nspname, pgtt_namespace_name) != 0)
{
if (strstr(nspname, "pg_temp") != NULL)
elog(ERROR, "a temporary table has been created and is active, can not add a comment on the GTT table in this session.");
}
break;
}
case T_AlterTableStmt:
{
/* Look for contrainst statement */
AlterTableStmt *stmt = (AlterTableStmt *)parsetree;
ListCell *lcmd;
Gtt gtt;
if (STMT_OBJTYPE(stmt) != OBJECT_TABLE)
break;
/* Look if the table is declared as GTT */
gtt.relid = 0;
GttHashTableLookup(stmt->relation->relname, gtt);
/* Not registered as a GTT, nothing to do here */
if (gtt.relid == 0)
break;
/* We do not allow foreign keys on global temporary table */
foreach(lcmd, stmt->cmds)
{
AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
if (cmd->subtype == AT_AddConstraint
#if (PG_VERSION_NUM < 130000)
|| cmd->subtype == AT_ProcessedConstraint
#endif
)
{
Constraint *constr = (Constraint *) cmd->def;
if (constr->contype == CONSTR_FOREIGN)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("attempt to create referential integrity constraint on global temporary table")));
}
}
break;
}
case T_IndexStmt:
{
/* CREATE INDEX statement */
IndexStmt *stmt = (IndexStmt *) parsetree;
Oid relid;
char *nspname;
relid = RangeVarGetRelidExtended(stmt->relation, ShareLock,
#if (PG_VERSION_NUM >= 110000)
0,
#else
false, false,
#endif
RangeVarCallbackOwnsRelation,
NULL);
/* Just take care that the GTT is not in use */
nspname = get_namespace_name(get_rel_namespace(relid));
if (is_declared_gtt(relid))
{
if (strcmp(nspname, pgtt_namespace_name) != 0)
{
if (strstr(nspname, "pg_temp") != NULL)
elog(ERROR, "a temporary table has been created and is active, can not add an index on the GTT table in this session.");
}
}
break;
}
default:
break;
}
return work_completed;
}
static void
gtt_ExecutorStart(QueryDesc *queryDesc, int eflags)
{
elog(DEBUG1, "gtt_ExecutorStart()");
/* Do not waste time here if the feature is not enabled for this session */
if (pgtt_is_enabled && NOT_IN_PARALLEL_WORKER)
{
/* Try to load pgtt if not already done. */
gtt_try_load();
/* check if we are working on a GTT and create it if it doesn't exist */
if (queryDesc->operation == CMD_INSERT
|| queryDesc->operation == CMD_DELETE
|| queryDesc->operation == CMD_UPDATE
|| queryDesc->operation == CMD_SELECT)
{
/* Verify if a GTT table is defined, create it if this is not already the case */
if (gtt_table_exists(queryDesc))
elog(DEBUG1, "ExecutorStart() statement use a Global Temporary Table");
}
}
elog(DEBUG1, "restore ExecutorStart()");
/* Continue the normal behavior */
if (prev_ExecutorStart)
prev_ExecutorStart(queryDesc, eflags);
else
standard_ExecutorStart(queryDesc, eflags);
elog(DEBUG1, "End of gtt_ExecutorStart()");
}
static bool
gtt_table_exists(QueryDesc *queryDesc)
{
bool is_gtt = false;
char *name = NULL;
char relpersistence;
RangeTblEntry *rte;
Relation rel;
Gtt gtt;
PlannedStmt *pstmt = (PlannedStmt *) queryDesc->plannedstmt;
if (GttHashTable == NULL || !pstmt)
return false;
/* no relation in rtable probably a function call */
if (list_length(pstmt->rtable) == 0)
return false;
/* This must be a valid relation and not a temporary table */
rte = (RangeTblEntry *) linitial(pstmt->rtable);
if (rte->relid != InvalidOid && rte->relkind == RELKIND_RELATION
&& !is_catalog_relid(rte->relid))
{
#if (PG_VERSION_NUM >= 120000)
rel = table_open(rte->relid, NoLock);
#else
rel = heap_open(rte->relid, NoLock);
#endif
name = RelationGetRelationName(rel);
relpersistence = rel->rd_rel->relpersistence;
#if (PG_VERSION_NUM >= 120000)
table_close(rel, NoLock);
#else
heap_close(rel, NoLock);
#endif
/* Do not go further with temporary tables, catalog or toast table */
if (relpersistence != RELPERSISTENCE_TEMP)
return false;
gtt.relid = 0;
gtt.temp_relid = 0;
gtt.relname[0] = '\0';
gtt.preserved = false;
gtt.code = NULL;
gtt.created = false;
/* Check if the table is in the hash list and it has not already be created */
if (PointerIsValid(name))
GttHashTableLookup(name, gtt);
elog(DEBUG1, "gtt_table_exists() looking for table \"%s\" with relid %d into cache.", name, rte->relid);
if (gtt.relname[0] != '\0')
{
elog(DEBUG1, "GTT found in cache with name: %s, relid: %d, temp_relid %d", gtt.relname, gtt.relid, gtt.temp_relid);
/* Create the temporary table if it does not exists */
if (!gtt.created)
{
elog(DEBUG1, "global temporary table does not exists create it: %s", gtt.relname);
/* Call create temporary table */
if ((gtt.temp_relid = create_temporary_table_internal(gtt.relid, gtt.preserved)) != InvalidOid)
{
elog(DEBUG1, "global temporary table %s (oid: %d) created", gtt.relname, gtt.temp_relid);
/* Update hash list with table flagged as created */
gtt.created = true;
GttHashTableDelete(gtt.relname);
GttHashTableInsert(gtt, gtt.relname);
}
else
elog(ERROR, "can not create global temporary table %s", gtt.relname);
}
is_gtt = true;
}
else
/* the table is not a global temporary table do nothing*/
elog(DEBUG1, "table \"%s\" not registered as GTT", name);
}
return is_gtt;
}
static bool
is_declared_gtt(Oid relid)
{
char *name = NULL;
char relpersistence;
Relation rel;
Gtt gtt;
if (GttHashTable == NULL)
return false;
/* This must be a valid relation and not a temporary table */
if (relid != InvalidOid && !is_catalog_relid(relid))
{
#if (PG_VERSION_NUM >= 120000)
rel = table_open(relid, NoLock);
#else
rel = heap_open(relid, NoLock);
#endif
name = RelationGetRelationName(rel);
relpersistence = rel->rd_rel->relpersistence;
#if (PG_VERSION_NUM >= 120000)
table_close(rel, NoLock);
#else
heap_close(rel, NoLock);
#endif
/* Do not go further with temporary tables, catalog or toast table */
if (relpersistence != RELPERSISTENCE_TEMP)
return false;
/* Check if the table is in the hash list and it has not already be created */
gtt.relid = 0;
gtt.temp_relid = 0;
gtt.relname[0] = '\0';
gtt.preserved = false;
gtt.code = NULL;
gtt.created = false;
if (PointerIsValid(name))
GttHashTableLookup(name, gtt);
if (gtt.relname[0] != '\0')
return true;
}
return false;
}
int
strpos(char *hay, char *needle, int offset)
{
char *haystack;
char *p;
haystack = (char *) malloc(strlen(hay));
if (haystack == NULL)
{
fprintf(stderr, "out of memory\n");
exit(EXIT_FAILURE);
return -1;
}
memset(haystack, 0, strlen(hay));
strncpy(haystack, hay+offset, strlen(hay)-offset);
p = strstr(haystack, needle);
if (p)
return p - haystack+offset;
return -1;
}
/*
* Create the Global Temporary Table with all associated objects
* by creating the template table and register the GTT in the
* pg_global_temp_tables table.
*
*/
static Oid
gtt_create_table_statement(Gtt gtt)
{
char *newQueryString = NULL;
int connected = 0;
int finished = 0;
int result = 0;
Oid gttOid = InvalidOid;
Datum oidDatum;
bool isnull;
elog(DEBUG1, "proceeding to Global Temporary Table creation.");
connected = SPI_connect();
if (connected != SPI_OK_CONNECT)
ereport(ERROR, (errmsg("could not connect to SPI manager")));
/* Create the "template" table */
newQueryString = psprintf("CREATE UNLOGGED TABLE %s.%s (%s)",
quote_identifier(pgtt_namespace_name),
quote_identifier(gtt.relname),
gtt.code);
result = SPI_exec(newQueryString, 0);
if (result < 0)
ereport(ERROR, (errmsg("execution failure on query: \"%s\"", newQueryString)));
/* Get Oid of the newly created table */
newQueryString = psprintf("SELECT c.relfilenode FROM pg_class c JOIN pg_namespace n ON (c.relnamespace=n.oid) WHERE c.relname='%s' AND n.nspname = '%s'",
gtt.relname,
pgtt_namespace_name);
result = SPI_exec(newQueryString, 0);
if (result != SPI_OK_SELECT && SPI_processed != 1)
ereport(ERROR, (errmsg("execution failure on query: \"%s\"", newQueryString)));
oidDatum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
if (!isnull)
gttOid = DatumGetInt32(oidDatum);
if (isnull || !OidIsValid(gttOid))
ereport(ERROR,
(errmsg("can not get OID of newly created GTT template table %s",
quote_identifier(gtt.relname))));
/* Now register the GTT table */
newQueryString = psprintf("INSERT INTO %s.pg_global_temp_tables VALUES (%d, '%s', '%s', '%c', %s)",
quote_identifier(pgtt_namespace_name),
gttOid,
pgtt_namespace_name,
gtt.relname,
(gtt.preserved) ? 't' : 'f',
quote_literal_cstr(gtt.code)
);
result = SPI_exec(newQueryString, 0);
if (result < 0)
ereport(ERROR, (errmsg("can not registrer new global temporary table")));
/* Set privilege on the unlogged table */
newQueryString = psprintf("GRANT ALL ON TABLE %s.%s TO public",
quote_identifier(pgtt_namespace_name),
quote_identifier(gtt.relname));
result = SPI_exec(newQueryString, 0);
if (result < 0)
ereport(ERROR, (errmsg("execution failure on query: \"%s\"", newQueryString)));
/* Mark the GTT as been created before register the table in the cache */
gtt.created = true;
finished = SPI_finish();
if (finished != SPI_OK_FINISH)
ereport(ERROR, (errmsg("could not disconnect from SPI manager")));
return gttOid;
}
/*
* Unregister a Global Temporary Table in pg_global_temp_tables table
* using his relid.
*/
static void
gtt_unregister_global_temporary_table(Oid relid, const char *relname)
{
RangeVar *rv;
Relation rel;
ScanKeyData key[1];
SysScanDesc scan;
HeapTuple tuple;
elog(DEBUG1, "Looking for registered GTT relid = %d, relname = %s", relid, relname);
/* Set and open the GTT relation */
rv = makeRangeVar(pgtt_namespace_name, CATALOG_GLOBAL_TEMP_REL, -1);
#if (PG_VERSION_NUM >= 120000)
rel = table_openrv(rv, RowExclusiveLock);
#else
rel = heap_openrv(rv, RowExclusiveLock);
#endif
/* Define scanning */
ScanKeyInit(&key[0], Anum_pgtt_relid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(relid));
/* Start search of relation */
scan = systable_beginscan(rel, 0, true, NULL, 1, key);
/* Remove the tuples. */
while (HeapTupleIsValid(tuple = systable_getnext(scan)))
{
elog(DEBUG1, "removing tuple with relid = %d and relname = %s", relid, relname);
simple_heap_delete(rel, &tuple->t_self);
}
/* Cleanup. */
systable_endscan(scan);
#if (PG_VERSION_NUM >= 120000)
table_close(rel, RowExclusiveLock);
#else
heap_close(rel, RowExclusiveLock);
#endif
}
/*
* Unregister a Global Temporary Table in pg_global_temp_tables table
* that is not cached and using his name only.
*/
static void
gtt_unregister_gtt_not_cached(const char *relname)
{
RangeVar *rv;
Relation rel;
ScanKeyData key[1];
SysScanDesc scan;
HeapTuple tuple;
elog(DEBUG1, "Looking for registered GTT relname = %s", relname);
/* Set and open the GTT relation */
rv = makeRangeVar(pgtt_namespace_name, CATALOG_GLOBAL_TEMP_REL, -1);
#if (PG_VERSION_NUM >= 120000)
rel = table_openrv(rv, RowExclusiveLock);
#else
rel = heap_openrv(rv, RowExclusiveLock);
#endif
/* Define scanning */
ScanKeyInit(&key[0], Anum_pgtt_relname, BTEqualStrategyNumber, F_NAMEEQ, CStringGetDatum(relname));
/* Start search of relation */
scan = systable_beginscan(rel, 0, true, NULL, 1, key);
/* Remove the tuples. */
while (HeapTupleIsValid(tuple = systable_getnext(scan)))
{
elog(DEBUG1, "removing tuple with relname = %s", relname);
simple_heap_delete(rel, &tuple->t_self);
}
/* Cleanup. */
systable_endscan(scan);
#if (PG_VERSION_NUM >= 120000)
table_close(rel, RowExclusiveLock);
#else
heap_close(rel, RowExclusiveLock);
#endif
}
/*
* Check if pgtt hasn't been loaded yet, and try to load it in that case.
*/
static void
gtt_try_load(void)
{
/*
* Don't try to load if the extension is disabled, if we can't do it now or
* if it's already loaded.
*/
if (!pgtt_is_enabled || !IsTransactionState() || GttHashTable != NULL)
return;
/* Initialize list of Global Temporary Table */
if (EnableGttManager())
{
/*
* Load temporary table definition from pg_global_temp_tables table
* into our Hash table and pre-create the temporary tables.
*/
gtt_load_global_temporary_tables();
/*
* Be sure that extension schema is at end of the search path so that
* "template" tables will be found.
*/
force_pgtt_namespace();
}
}
#if PG_VERSION_NUM < 160000
/*
* From src/backend/commands/extension.c
*/
Oid
get_extension_schema(Oid ext_oid)
{
Oid result;
Relation rel;
SysScanDesc scandesc;
HeapTuple tuple;
ScanKeyData entry[1];
#if (PG_VERSION_NUM >= 120000)
rel = table_open(ExtensionRelationId, AccessShareLock);
#else
rel = heap_open(ExtensionRelationId, AccessShareLock);
#endif
ScanKeyInit(&entry[0],
#if (PG_VERSION_NUM >= 120000)
Anum_pg_extension_oid,
#else
ObjectIdAttributeNumber,
#endif
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(ext_oid));
scandesc = systable_beginscan(rel, ExtensionOidIndexId, true,
NULL, 1, entry);
tuple = systable_getnext(scandesc);
/* We assume that there can be at most one matching tuple */
if (HeapTupleIsValid(tuple))
result = ((Form_pg_extension) GETSTRUCT(tuple))->extnamespace;
else
result = InvalidOid;
systable_endscan(scandesc);
#if (PG_VERSION_NUM >= 120000)
table_close(rel, AccessShareLock);
#else
heap_close(rel, AccessShareLock);
#endif
return result;
}
#endif
/*
* EnableGttManager
* Enables the GTT management cache at backend startup.
*/
bool
EnableGttManager(void)
{
Oid extOid = get_extension_oid("pgtt", true);
RangeVar *rv;
char *nspname;
if (!OidIsValid(extOid))
return false;
pgtt_namespace_oid = get_extension_schema(extOid);
if (!OidIsValid(pgtt_namespace_oid))
elog(ERROR, "namespace %d can not be found.", pgtt_namespace_oid);
/*
* Check if the GTT relation also exist. We might be in the middle of the
* extension creation, where the line in pg_extension exists but not the
* rest of SQL objects.
*/
nspname = get_namespace_name(pgtt_namespace_oid);
rv = makeRangeVar(nspname, CATALOG_GLOBAL_TEMP_REL, -1);
if (!OidIsValid(RangeVarGetRelid(rv, AccessShareLock, true)))
return false;
if (GttHashTable == NULL)
{
HASHCTL ctl;
MemSet(&ctl, 0, sizeof(ctl));
ctl.keysize = NAMEDATALEN;
ctl.entrysize = sizeof(GttHashEnt);
/* allocate GTT Cache in the cache context */
ctl.hcxt = CacheMemoryContext;
GttHashTable = hash_create("Global Temporary Table hash list",
GTT_PER_DATABASE,
&ctl,
#if PG_VERSION_NUM >= 140000
HASH_STRINGS | HASH_ELEM | HASH_CONTEXT
#else
HASH_ELEM | HASH_CONTEXT
#endif
);
elog(DEBUG1, "GTT cache initialized.");
}
/*
* Set the OID and name of the extension schema, all objects will be
* created in this schema.
*/
strcpy(pgtt_namespace_name, nspname);
return true;
}
/*
* Delete all declared Global Temporary Table.
*
*/
void
GttHashTableDeleteAll(void)
{
HASH_SEQ_STATUS status;
GttHashEnt *lentry = NULL;
if (GttHashTable == NULL)
return;
hash_seq_init(&status, GttHashTable);
while ((lentry = (GttHashEnt *) hash_seq_search(&status)) != NULL)
{
Gtt gtt = GetGttByName(lentry->name);
elog(DEBUG1, "Remove GTT %s from our hash table", gtt.relname);
GttHashTableDelete(lentry->name);
/* Restart the iteration in case that led to other drops */
hash_seq_term(&status);
hash_seq_init(&status, GttHashTable);
}
}
/*
* GetGttByName
* Returns a Gtt given a table name, or NULL if name is not found.
*
* Caller should have made sure that GTT has been properly loaded before
* calling this function.
*/
Gtt
GetGttByName(const char *name)
{
Gtt gtt;
Assert(GttHashTable != NULL);
if (PointerIsValid(name))
GttHashTableLookup(name, gtt);
return gtt;
}
/*
* Load Global Temporary Table in memory from pg_global_temp_tables table.
*/
static void
gtt_load_global_temporary_tables(void)
{
RangeVar *rv;
Relation rel;
#if (PG_VERSION_NUM >= 120000)
TableScanDesc scan;
#else
HeapScanDesc scan;
#endif
HeapTuple tuple;
int numberOfAttributes;
TupleDesc tupleDesc;
Snapshot snapshot;
elog(DEBUG1, "gtt_load_global_temporary_tables()");
elog(DEBUG1, "retrieve GTT list from definition table %s.%s", pgtt_namespace_name, CATALOG_GLOBAL_TEMP_REL);
/* Set and open the GTT definition storage relation */
rv = makeRangeVar(pgtt_namespace_name, CATALOG_GLOBAL_TEMP_REL, -1);
/* Open the CATALOG_GLOBAL_TEMP_REL table. We don't want to allow
* writable accesses by other session during import. */
PushActiveSnapshot(GetTransactionSnapshot());
snapshot = GetActiveSnapshot();
#if (PG_VERSION_NUM >= 120000)
rel = table_openrv(rv, AccessShareLock);
scan = table_beginscan(rel, snapshot, 0, (ScanKey) NULL);
#else
rel = heap_openrv(rv, AccessShareLock);
scan = heap_beginscan(rel, snapshot, 0, (ScanKey) NULL);
#endif
tupleDesc = RelationGetDescr(rel);
numberOfAttributes = tupleDesc->natts;
while (HeapTupleIsValid(tuple = heap_getnext(scan, ForwardScanDirection)))
{
Gtt gtt;
Datum *values = (Datum *) palloc(numberOfAttributes * sizeof(Datum));
bool *isnull = (bool *) palloc(numberOfAttributes * sizeof(bool));
/* Extract data */
heap_deform_tuple(tuple, tupleDesc, values, isnull);
gtt.relid = DatumGetInt32(values[0]);
strcpy(gtt.relname, NameStr(*(DatumGetName(values[2]))));
gtt.preserved = DatumGetBool(values[3]);
gtt.code = TextDatumGetCString(values[4]);
gtt.created = false;
gtt.temp_relid = 0;
/* Add table to cache */
GttHashTableInsert(gtt, gtt.relname);
}
/* Cleanup. */
#if (PG_VERSION_NUM >= 120000)
table_endscan(scan);
table_close(rel, AccessShareLock);
#else
heap_endscan(scan);
heap_close(rel, AccessShareLock);
#endif
PopActiveSnapshot();
}
static Oid
create_temporary_table_internal(Oid parent_relid, bool preserved)
{
/* Value to be returned */
Oid temp_relid = InvalidOid; /* safety */
#if (PG_VERSION_NUM >= 130000)
ObjectAddress address;
#endif
/* Parent's namespace and name */
Oid parent_nsp;
char *parent_name,
*parent_nsp_name;
char parent_persistence;
/* Elements of the "CREATE TABLE" query tree */
RangeVar *parent_rv;
RangeVar *table_rv;
TableLikeClause *like_clause = makeNode(TableLikeClause);
CreateStmt *createStmt = makeNode(CreateStmt);
List *createStmts;
ListCell *lc;
elog(DEBUG1, "creating a temporary table like table with Oid %d", parent_relid);
/* Lock parent and check if it exists */
LockRelationOid(parent_relid, ShareUpdateExclusiveLock);
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(parent_relid)))
elog(ERROR, "relation %u does not exist", parent_relid);
/* Cache parent's namespace and name */
parent_name = get_rel_name(parent_relid);
parent_nsp = get_rel_namespace(parent_relid);
parent_nsp_name = get_namespace_name(parent_nsp);
parent_persistence = get_rel_persistence(parent_relid);
/* Make up parent's RangeVar */
parent_rv = makeRangeVar(parent_nsp_name, parent_name, -1);
parent_rv->relpersistence = parent_persistence;
elog(DEBUG1, "Parent namespace: %s, parent relname: %s, parent oid: %d",
parent_rv->schemaname,
parent_rv->relname,
parent_relid);
/* Set name of temporary table same as parent table */
table_rv = makeRangeVar("pg_temp", parent_rv->relname, -1);
Assert(table_rv);
elog(DEBUG1, "Initialize TableLikeClause structure");
/* Initialize TableLikeClause structure */
like_clause->relation = copyObject(parent_rv);
like_clause->options = CREATE_TABLE_LIKE_DEFAULTS
| CREATE_TABLE_LIKE_INDEXES
| CREATE_TABLE_LIKE_CONSTRAINTS
#if (PG_VERSION_NUM >= 100000)
| CREATE_TABLE_LIKE_IDENTITY
#endif
#if (PG_VERSION_NUM >= 120000)
| CREATE_TABLE_LIKE_GENERATED
#endif
| CREATE_TABLE_LIKE_COMMENTS;
elog(DEBUG1, "Initialize CreateStmt structure");
/* Initialize CreateStmt structure */
createStmt->relation = copyObject(table_rv);
createStmt->relation->schemaname = NULL;
createStmt->relation->relpersistence = RELPERSISTENCE_TEMP;
createStmt->tableElts = list_make1(copyObject(like_clause));
createStmt->inhRelations = NIL;
createStmt->ofTypename = NULL;
createStmt->constraints = NIL;
createStmt->options = NIL;
#if (PG_VERSION_NUM >= 120000)
createStmt->accessMethod = NULL;
#endif
if (preserved)
createStmt->oncommit = ONCOMMIT_PRESERVE_ROWS;
else
createStmt->oncommit = ONCOMMIT_DELETE_ROWS;
createStmt->tablespacename = NULL;
createStmt->if_not_exists = false;
elog(DEBUG1, "Obtain the sequence of Stmts to create temporary table");
/* Obtain the sequence of Stmts to create temporary table */
createStmts = transformCreateStmt(createStmt, NULL);
elog(DEBUG1, "Processing list of statements");
/* Create the temporary table */
foreach (lc, createStmts)
{
/* Fetch current CreateStmt */
Node *cur_stmt = (Node *) lfirst(lc);
elog(DEBUG1, "Processing statement of type %d", nodeTag(cur_stmt));
if (IsA(cur_stmt, CreateStmt))
{
Datum toast_options;
#if PG_VERSION_NUM < 180000
static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
#else
const char *validnsps[] = HEAP_RELOPT_NAMESPACES;
#endif
Oid temp_relowner;
/* Temporary table owner must be current user */
temp_relowner = GetUserId();
elog(DEBUG1, "Creating a temporary table and get its Oid");
/* Create a temporary table and save its Oid */
#if (PG_VERSION_NUM < 100000)
temp_relid = DefineRelation((CreateStmt *) cur_stmt, RELKIND_RELATION, temp_relowner, NULL).objectId;
#elif (PG_VERSION_NUM < 130000)
temp_relid = DefineRelation((CreateStmt *) cur_stmt, RELKIND_RELATION, temp_relowner, NULL, NULL).objectId;
#else
address = DefineRelation((CreateStmt *) cur_stmt, RELKIND_RELATION, temp_relowner, NULL, NULL);
temp_relid = address.objectId;
#endif
/* Update config one more time */
CommandCounterIncrement();
/*
* parse and validate reloptions for the toast
* table
*/
toast_options = transformRelOptions((Datum) 0,
((CreateStmt *) cur_stmt)->options,
"toast",
validnsps,
true,
false);
(void) heap_reloptions(RELKIND_TOASTVALUE, toast_options, true);
NewRelationCreateToastTable(temp_relid, toast_options);
}
else if (IsA(cur_stmt, IndexStmt))
{
Oid relid;
elog(DEBUG1, "execution statement CREATE INDEX, relation has an index.");
relid =
RangeVarGetRelidExtended(((IndexStmt *) cur_stmt)->relation, ShareLock,
#if (PG_VERSION_NUM >= 110000)
0,
#else
false, false,
#endif
RangeVarCallbackOwnsRelation,
NULL);
DefineIndex(relid, /* OID of heap relation */
(IndexStmt *) cur_stmt,
InvalidOid, /* no predefined OID */
#if (PG_VERSION_NUM >= 110000)
InvalidOid, /* no parent index */
InvalidOid, /* no parent constraint */
#endif
#if (PG_VERSION_NUM >= 160000)
-1,/* total parts */
#endif
false, /* is_alter_table */
true, /* check_rights */
#if (PG_VERSION_NUM > 100000)
true, /* check_not_in_use */
#endif
false, /* skip_build */
false); /* quiet */
}
else if (IsA(cur_stmt, CommentStmt))
{
CommentObject((CommentStmt *) cur_stmt);
}
#if (PG_VERSION_NUM >= 90600)
else if (IsA(cur_stmt, TableLikeClause))
{
TableLikeClause *like = (TableLikeClause *) cur_stmt;
RangeVar *rv = createStmt->relation;
List *morestmts;
morestmts = expandTableLikeClause(rv, like);
createStmts = list_concat(createStmts, morestmts);
/* don't need a CCI now */
continue;
}
#endif
else
{
/*
* Recurse for anything else.
*/
#if PG_VERSION_NUM >= 100000
PlannedStmt *stmt = makeNode(PlannedStmt);
stmt->commandType = CMD_UTILITY;
stmt->canSetTag = true;
stmt->utilityStmt = cur_stmt;
stmt->stmt_location = -1;
stmt->stmt_len = 0;
ProcessUtility(stmt,
"PGTT provide a query string",
#if PG_VERSION_NUM >= 140000
false,
#endif
PROCESS_UTILITY_SUBCOMMAND,
NULL, NULL,
None_Receiver,
NULL);
#else
ProcessUtility(cur_stmt,
"PGTT provide a query string",
#if PG_VERSION_NUM >= 140000
false,
#endif
PROCESS_UTILITY_SUBCOMMAND,
NULL,
None_Receiver,
NULL);
#endif
}
/* Need CCI between commands */
#if (PG_VERSION_NUM < 130000)
if (lnext(lc) != NULL)
#else
if (lnext(createStmts, lc) != NULL)
#endif
CommandCounterIncrement();
}
/* release lock on "template" relation */
UnlockRelationOid(parent_relid, ShareUpdateExclusiveLock);
elog(DEBUG1, "Create a temporary table done with Oid: %d", temp_relid);
return temp_relid;
}
/*
* Post-parse-analysis hook: mark query with a queryId
*/
static void
#if PG_VERSION_NUM >= 140000
gtt_post_parse_analyze(ParseState *pstate, Query *query, struct JumbleState * jstate)
#else
gtt_post_parse_analyze(ParseState *pstate, Query *query)
#endif
{
/* Try to load pgtt if not already done. */
gtt_try_load();
if (NOT_IN_PARALLEL_WORKER && pgtt_is_enabled && query->rtable != NIL &&
GttHashTable != NULL)
{
/* replace the Oid of the template table by our new table in the rtable */
RangeTblEntry *rte = (RangeTblEntry *) linitial(query->rtable);
Relation rel;
Gtt gtt;
char *name = NULL;
/* This must be a valid relation not from pg_catalog*/
if (rte->relid != InvalidOid && rte->relkind == RELKIND_RELATION
&& !is_catalog_relid(rte->relid))
{
#if (PG_VERSION_NUM >= 120000)
rel = table_open(rte->relid, NoLock);
#else
rel = heap_open(rte->relid, NoLock);
#endif
name = RelationGetRelationName(rel);
#if (PG_VERSION_NUM >= 120000)
table_close(rel, NoLock);
#else
heap_close(rel, NoLock);
#endif
gtt.relid = 0;
gtt.temp_relid = 0;
gtt.relname[0] = '\0';
gtt.preserved = false;
gtt.code = NULL;
gtt.created = false;
/* Check if the table is in the hash list and it has not already be created */
if (PointerIsValid(name))
{
elog(DEBUG1, "gtt_post_parse_analyze() looking for table \"%s\" with relid %d into cache.", name, rte->relid);
GttHashTableLookup(name, gtt);
}
else
elog(ERROR, "gtt_post_parse_analyze() table to search in cache is not valide pointer, relid: %d.", rte->relid);
if (gtt.relname[0] != '\0')
{
/* After an error and rollback the table is still registered in cache but must be initialized */
if (gtt.created && OidIsValid(gtt.temp_relid)
&& !SearchSysCacheExists1(RELOID, ObjectIdGetDatum(gtt.temp_relid))
)
{
elog(DEBUG1, "invalid temporary table with relid %d (%s), reseting.", gtt.temp_relid, gtt.relname);
gtt.created = false;
gtt.temp_relid = 0;
}
/* Create the temporary table if it does not exists */
if (!gtt.created)
{
elog(DEBUG1, "global temporary table from relid %d does not exists create it: %s", rte->relid, gtt.relname);
/* Call create temporary table */
if ((gtt.temp_relid = create_temporary_table_internal(gtt.relid, gtt.preserved)) != InvalidOid)
{
elog(DEBUG1, "global temporary table %s (oid: %d) created", gtt.relname, gtt.temp_relid);
/* Update hash list with table flagged as created*/
gtt.created = true;
GttHashTableDelete(gtt.relname);
GttHashTableInsert(gtt, gtt.relname);
}
else
elog(ERROR, "can not create global temporary table %s", gtt.relname);
}
elog(DEBUG1, "temporary table exists with oid %d", gtt.temp_relid);
if (rte->relid != gtt.temp_relid)
{
#if PG_VERSION_NUM >= 160000
RTEPermissionInfo *rteperm = list_nth(query->rteperminfos,
rte->perminfoindex - 1);
rteperm->relid = gtt.temp_relid;
#endif
LockRelationOid(gtt.temp_relid, rte->rellockmode);
if (rte->rellockmode != AccessShareLock)
UnlockRelationOid(rte->relid, rte->rellockmode);
rte->relid = gtt.temp_relid;
elog(DEBUG1, "rerouting relid %d access to %d for GTT table \"%s\"", rte->relid, gtt.temp_relid, name);
}
}
else
/* the table is not a global temporary table do nothing*/
elog(DEBUG1, "table \"%s\" not registered as GTT", name);
}
}
/* restore hook */
if (prev_post_parse_analyze_hook) {
#if PG_VERSION_NUM >= 140000
prev_post_parse_analyze_hook(pstate, query, jstate);
#else
prev_post_parse_analyze_hook(pstate, query);
#endif
}
}
static bool
is_catalog_relid(Oid relid)
{
HeapTuple reltup;
Form_pg_class relform;
Oid relnamespace;
reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
if (!HeapTupleIsValid(reltup))
elog(ERROR, "cache lookup failed for relation %u", relid);
relform = (Form_pg_class) GETSTRUCT(reltup);
relnamespace = relform->relnamespace;
ReleaseSysCache(reltup);
if (relnamespace == PG_CATALOG_NAMESPACE || relnamespace == PG_TOAST_NAMESPACE)
{
elog(DEBUG1, "relation %d is in pg_catalog or pg_toast schema, nothing to do.", relid);
return true;
}
return false;
}
/*
* Be sure that extension schema is at end of the search path so that
* "template" tables will be found.
*/
static void
force_pgtt_namespace(void)
{
bool override = false;
char *old_search_path;
const char *pgtt_schema = quote_identifier(pgtt_namespace_name);
StringInfoData search_path;
if (!IsTransactionState() || GttHashTable == NULL)
return;
initStringInfo(&search_path);
old_search_path = GetConfigOptionByName("search_path", NULL, false);
if (old_search_path == NULL)
{
appendStringInfo(&search_path, "%s", pgtt_schema);
override = true;
}
else if (strlen(old_search_path) > 0 && strstr(old_search_path, pgtt_schema) == NULL)
{
/*
* first look if pg_catalog is at end of the search path to keep
* it at end. This is not the same behavior if it not kept at the
* end when there is pg_catalog functions overloaded in another
* schema
*/
bool at_end = false;
int len = strlen(old_search_path) - 10;
char *p = strstr(old_search_path, "pg_catalog");
if (p != NULL && strcmp(p, "pg_catalog") == 0)
{
/* remove redundant whitespaces */
while (len > 0 && isspace(old_search_path[len - 1]))
len--;
old_search_path[len] = '\0';
appendStringInfo(&search_path, "%s %s", old_search_path, pgtt_schema);
at_end = true;
}
else
{
appendStringInfo(&search_path, "%s, %s", old_search_path, pgtt_schema);
}
if (at_end)
appendStringInfo(&search_path, ", pg_catalog");
override = true;
}
if (override)
{
/* Override the search_path by adding our pgtt schema. */
SetConfigOption("search_path", search_path.data,
(superuser() ? PGC_SUSET : PGC_USERSET),
PGC_S_SESSION);
elog(DEBUG1, "search_path forced to %s.", search_path.data);
}
}
/*
* Update a registered Global Temporary Table
* in the pg_global_temp_tables table.
*
*/
static void
gtt_update_registered_table(Gtt gtt)
{
char *newQueryString = NULL;
int connected = 0;
int finished = 0;
int result = 0;
elog(DEBUG1, "proceeding to Global Temporary Table creation.");
connected = SPI_connect();
if (connected != SPI_OK_CONNECT)
ereport(ERROR, (errmsg("could not connect to SPI manager")));
newQueryString = psprintf("UPDATE %s.pg_global_temp_tables SET relname = '%s' WHERE relid = %d",
quote_identifier(pgtt_namespace_name),
gtt.relname,
gtt.relid
);
result = SPI_exec(newQueryString, 0);
if (result < 0)
ereport(ERROR,
(errmsg("can not update relid %d into %s.pg_global_temp_tables",
gtt.relid, quote_identifier(pgtt_namespace_name))));
finished = SPI_finish();
if (finished != SPI_OK_FINISH)
ereport(ERROR, (errmsg("could not disconnect from SPI manager")));
}
/*
* Create the temporary table related to a Global Temporary Table
* and register the GTT in pg_global_temp_tables table.
*
*/
static void
gtt_create_table_as(Gtt gtt, bool skipdata)
{
char *newQueryString = NULL;
int connected = 0;
int finished = 0;
int result = 0;
Oid gttOid = InvalidOid;
Datum oidDatum;
bool isnull;
elog(DEBUG1, "proceeding to Global Temporary Table creation.");
/* This can only be called if GTT has been properly loaded. */
Assert(GttHashTable != NULL);
connected = SPI_connect();
if (connected != SPI_OK_CONNECT)
ereport(ERROR, (errmsg("could not connect to SPI manager")));
/* Create the "template" table */
newQueryString = psprintf("CREATE UNLOGGED TABLE %s.%s %s;",
quote_identifier(pgtt_namespace_name),
quote_identifier(gtt.relname),
gtt.code);
result = SPI_exec(newQueryString, 0);
if (result < 0)
ereport(ERROR, (errmsg("execution failure on query: \"%s\"", newQueryString)));
/* Get Oid of the newly created table */
newQueryString = psprintf("SELECT c.relfilenode FROM pg_class c JOIN pg_namespace n ON (c.relnamespace=n.oid) WHERE c.relname='%s' AND n.nspname = '%s'",
gtt.relname,
pgtt_namespace_name);
result = SPI_exec(newQueryString, 0);
if (result != SPI_OK_SELECT && SPI_processed != 1)
ereport(ERROR, (errmsg("execution failure on query: \"%s\"", newQueryString)));
oidDatum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
if (!isnull)
gttOid = DatumGetInt32(oidDatum);
if (isnull || !OidIsValid(gttOid))
ereport(ERROR,
(errmsg("can not get OID of newly created GTT template table %s",
quote_identifier(gtt.relname))));
gtt.relid = gttOid;
/* Create the temporary table only if data from source table must be inserted */
if (!skipdata)
{
char namespaceName[NAMEDATALEN];
/* Get current temporary namespace name */
snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d",
#if PG_VERSION_NUM < 170000
MyBackendId
#else
MyProcNumber
#endif
);
newQueryString = psprintf("CREATE TEMPORARY TABLE %s %s WITH DATA",
quote_identifier(gtt.relname),
gtt.code);
result = SPI_exec(newQueryString, 0);
if (result < 0)
ereport(ERROR, (errmsg("execution failure on query: \"%s\"", newQueryString)));
/* Get Oid of the newly created temporary table */
newQueryString = psprintf("SELECT c.relfilenode FROM pg_class c JOIN pg_namespace n ON (c.relnamespace=n.oid) WHERE c.relname='%s' AND n.nspname = '%s'",
gtt.relname,
namespaceName);
result = SPI_exec(newQueryString, 0);
if (result != SPI_OK_SELECT && SPI_processed != 1)
ereport(ERROR, (errmsg("execution failure on query: \"%s\"", newQueryString)));
oidDatum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
if (!isnull)
gtt.temp_relid = DatumGetInt32(oidDatum);
if (isnull || !OidIsValid(gttOid))
ereport(ERROR,
(errmsg("can not get OID of newly created temporary table %s",
quote_identifier(gtt.relname))));
gtt.created = true;
}
/* Now register the GTT table */
newQueryString = psprintf("INSERT INTO %s.pg_global_temp_tables VALUES (%d, '%s', '%s', '%c', %s)",
quote_identifier(pgtt_namespace_name),
gtt.relid,
pgtt_namespace_name,
gtt.relname,
(gtt.preserved) ? 't' : 'f',
quote_literal_cstr(gtt.code)
);
result = SPI_exec(newQueryString, 0);
if (result < 0)
ereport(ERROR, (errmsg("can not registrer new global temporary table")));
finished = SPI_finish();
if (finished != SPI_OK_FINISH)
ereport(ERROR, (errmsg("could not disconnect from SPI manager")));
/* registrer the table in the cache */
GttHashTableDelete(gtt.relname);
GttHashTableInsert(gtt, gtt.relname);
}
int
strremovestr(char *src, char *toremove)
{
while( *src )
{
char *k=toremove,*s=src;
while( *k && *k==*s ) ++k,++s;
if( !*k )
{
while( *s ) *src++=*s++;
*src=0;
return 1;
}
++src;
}
return 0;
}
|