-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathpgtt.c
executable file
·2191 lines (1905 loc) · 61.5 KB
/
pgtt.c
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
/*-------------------------------------------------------------------------
*
* pgtt.c
* Add support to Oracle-style Global Temporary Table in PostgreSQL.
*
* Author: Gilles Darold <gilles@darold.net>
* Licence: PostgreSQL
* Copyright (c) 2018-2024, 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");
}
}