-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathddl.c
1903 lines (1616 loc) · 47.7 KB
/
ddl.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
/*----------------------------------------------------------------------------
*
* ddl.c
* Statement based replication of DDL commands.
*
* Copyright (c) 2019-2020, Postgres Professional
*
*----------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/relscan.h"
#include "access/table.h"
#include "access/tableam.h"
#include "access/heapam.h"
#include "access/genam.h"
#include "utils/guc_tables.h"
#include "tcop/utility.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "executor/executor.h"
#include "catalog/pg_proc.h"
#ifdef PGPROEE
#include "commands/partition.h"
#endif
#include "commands/tablecmds.h"
#include "parser/parse_type.h"
#include "parser/parse_func.h"
#include "commands/sequence.h"
#include "tcop/pquery.h"
#include "utils/snapmgr.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_namespace.h"
#include "executor/spi.h"
#include "utils/lsyscache.h"
#include "catalog/indexing.h"
#include "commands/tablespace.h"
#include "commands/typecmds.h"
#include "parser/parse_utilcmd.h"
#include "commands/defrem.h"
#include "utils/regproc.h"
#include "replication/message.h"
#include "access/relscan.h"
#include "commands/vacuum.h"
#include "pgstat.h"
#include "utils/inval.h"
#include "utils/builtins.h"
#include "replication/origin.h"
#include "catalog/pg_authid.h"
#include "storage/ipc.h"
#include "miscadmin.h"
#include "ddl.h"
#include "logger.h"
#include "commit.h"
#include "multimaster.h"
/* XXX: is it defined somewhere? */
#define GUC_KEY_MAXLEN 255
#define MTM_GUC_HASHSIZE 100
#define MULTIMASTER_MAX_LOCAL_TABLES 256
#define Natts_mtm_local_tables 2
#define Anum_mtm_local_tables_rel_schema 1
#define Anum_mtm_local_tables_rel_name 2
struct DDLSharedState
{
LWLock *localtab_lock;
} *ddl_shared;
typedef struct MtmGucEntry
{
char key[GUC_KEY_MAXLEN];
dlist_node list_node;
} MtmGucEntry;
typedef struct
{
NameData schema;
NameData name;
} MtmLocalTablesTuple;
/* GUCs */
bool MtmVolksWagenMode;
bool MtmMonotonicSequences;
char *MtmRemoteFunctionsList;
bool MtmIgnoreTablesWithoutPk;
MtmDDLInProgress DDLApplyInProgress;
static char MtmTempSchema[NAMEDATALEN];
static bool TempDropRegistered;
static int TempDropAtxLevel;
static void const *MtmDDLStatement;
static Node *MtmCapturedDDL;
static HTAB *MtmGucHash = NULL;
static dlist_head MtmGucList = DLIST_STATIC_INIT(MtmGucList);
static HTAB *MtmRemoteFunctions;
static bool MtmRemoteFunctionsValid;
static HTAB *MtmLocalTables;
static ExecutorStart_hook_type PreviousExecutorStartHook;
static ExecutorFinish_hook_type PreviousExecutorFinishHook;
static ProcessUtility_hook_type PreviousProcessUtilityHook;
static seq_nextval_hook_t PreviousSeqNextvalHook;
/* Set given temp namespace in receiver */
PG_FUNCTION_INFO_V1(mtm_set_temp_schema);
static void MtmSeqNextvalHook(Oid seqid, int64 next);
static void MtmExecutorStart(QueryDesc *queryDesc, int eflags);
static void MtmExecutorFinish(QueryDesc *queryDesc);
static void MtmProcessUtility(PlannedStmt *pstmt, const char *queryString,
ProcessUtilityContext context, ParamListInfo params,
QueryEnvironment *queryEnv, DestReceiver *dest,
QueryCompletion *qc);
static void MtmProcessUtilityReceiver(PlannedStmt *pstmt,
const char *queryString,
ProcessUtilityContext context, ParamListInfo params,
QueryEnvironment *queryEnv, DestReceiver *dest,
QueryCompletion *qc);
static void MtmProcessUtilitySender(PlannedStmt *pstmt,
const char *queryString,
ProcessUtilityContext context, ParamListInfo params,
QueryEnvironment *queryEnv, DestReceiver *dest,
QueryCompletion *qc);
static void MtmGucUpdate(const char *key);
static void MtmInitializeRemoteFunctionsMap(void);
static char *MtmGucSerialize(void);
static void MtmMakeRelationLocal(Oid relid, bool locked);
static List *AdjustCreateSequence(List *options);
static void MtmProcessDDLCommand(char const *queryString, bool transactional,
bool concurrent);
static void MtmFinishDDLCommand(void);
PG_FUNCTION_INFO_V1(mtm_make_table_local);
/*****************************************************************************
*
* Init
*
*****************************************************************************/
void
MtmDDLReplicationInit()
{
Size size = 0;
size = add_size(size, sizeof(struct DDLSharedState));
size = add_size(size, hash_estimate_size(MULTIMASTER_MAX_LOCAL_TABLES,
sizeof(Oid)));
size = MAXALIGN(size);
RequestAddinShmemSpace(size);
RequestNamedLWLockTranche("mtm-ddl", 1);
PreviousExecutorStartHook = ExecutorStart_hook;
ExecutorStart_hook = MtmExecutorStart;
PreviousExecutorFinishHook = ExecutorFinish_hook;
ExecutorFinish_hook = MtmExecutorFinish;
PreviousProcessUtilityHook = ProcessUtility_hook;
ProcessUtility_hook = MtmProcessUtility;
PreviousSeqNextvalHook = SeqNextvalHook;
SeqNextvalHook = MtmSeqNextvalHook;
}
void
MtmDDLReplicationShmemStartup(void)
{
HASHCTL info;
bool found;
memset(&info, 0, sizeof(info));
info.entrysize = info.keysize = sizeof(Oid);
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
ddl_shared = ShmemInitStruct("ddl",
sizeof(struct DDLSharedState),
&found);
if (!found)
{
ddl_shared->localtab_lock = &(GetNamedLWLockTranche("mtm-ddl"))->lock;
}
MtmLocalTables = ShmemInitHash("MtmLocalTables",
MULTIMASTER_MAX_LOCAL_TABLES, MULTIMASTER_MAX_LOCAL_TABLES,
&info, HASH_ELEM | HASH_BLOBS);
LWLockRelease(AddinShmemInitLock);
}
/*****************************************************************************
*
* Temp DDL handling.
*
* EE version allows to prepare transactions with temporary objects. Data of
* temp tables will not be decoded, but DDL will and must be sent to peer
* nodes. That allows to handle such cases as:
* * CREATE (persistent) table AS (temporary) -- receiver needs definition
* of previous temp table to create current persistent.
* * CREATE FUNCTION foo(x my_temp_table) -- same
* * DROP (persistent) object RECURSIVE -- can touch to some temp object.
*
* Each backend along with DDL to be replicated sends call to
* `select mtm.set_temp_schema('%s');` where %s constructed out of node_id and
* backend_id. Upon exit backends are write 'DROP SCHEMA ...' logical message
* commanding receivers to drop all temp stuff produced by that backend.
*
* Each receiver during execution of ddl will come across `set_temp_schema()`
* and will create or set mentioned namespace as temporary (in a same way as
* parallel workers do that). After transaction execution on_commit_actions
* also should be cleaned (see comments in apply code).
*
*****************************************************************************/
/*
* Log command to peers to remove all my temp schemas on apply. This ensures
* garbage mm temp schemas won't accumulate on node crash-restart.
*/
void
temp_schema_reset_all(int my_node_id)
{
char *query;
query = psprintf("do $$ "
"declare "
" nsp record; "
"begin "
" reset session_authorization; "
" for nsp in select nspname from pg_namespace where "
" nspname ~ '^mtm_tmp_%d_.*' and"
" nspname !~ '_toast$' loop "
" perform mtm.set_temp_schema(nsp.nspname); "
" execute format('drop schema if exists %%I cascade', nsp.nspname||'_toast'); "
" execute format('drop schema if exists %%I cascade', nsp.nspname); "
" end loop; "
"end $$; ",
my_node_id);
MtmProcessDDLCommand(query, false, false);
}
/* Drop temp schemas on peer nodes */
void
temp_schema_reset(bool transactional)
{
Assert(TempDropRegistered);
Assert(TempDropAtxLevel == MtmTxAtxLevel);
/*
* reset session_authorization restores permissions if previous ddl
* dropped them; set_temp_schema allows us to see temporary objects,
* otherwise they can't be dropped
*
* If drop is due to DISCARD, it is important to run it as 'V', otherwise
* it might interfere with later or earlier command using the schema.
*/
MtmProcessDDLCommand(
psprintf("RESET session_authorization; "
"select mtm.set_temp_schema('%s', false); "
"DROP SCHEMA IF EXISTS %s_toast CASCADE; "
"DROP SCHEMA IF EXISTS %s CASCADE;",
MtmTempSchema, MtmTempSchema, MtmTempSchema),
transactional,
false
);
MtmFinishDDLCommand();
}
/* Exit callback to call temp_schema_reset() */
static void
temp_schema_at_exit(int status, Datum arg)
{
Assert(TempDropRegistered);
AbortOutOfAnyTransaction();
StartTransactionCommand();
for (; MtmTxAtxLevel >= 0; MtmTxAtxLevel--)
{
temp_schema_init();
temp_schema_reset(false);
}
CommitTransactionCommand();
}
/* Register cleanup callback and generate temp schema name */
void
temp_schema_init(void)
{
if (!TempDropRegistered)
{
TempDropRegistered = true;
before_shmem_exit(temp_schema_at_exit, (Datum) 0);
}
if (MtmTxAtxLevel == 0)
snprintf(MtmTempSchema, sizeof(MtmTempSchema),
"mtm_tmp_%d_%d", Mtm->my_node_id, MyBackendId);
else
snprintf(MtmTempSchema, sizeof(MtmTempSchema),
"mtm_tmp_%d_%d_%d", Mtm->my_node_id, MyBackendId, MtmTxAtxLevel);
TempDropAtxLevel = MtmTxAtxLevel;
}
/*
* temp_schema_valid check format of temp schema name.
* Namespace name should be either mtm_tmp_\d+_\d+ or
* mtm_tmp_\d+_\d+_\d+ for non-zero atx level.
*/
static bool
temp_schema_valid(const char *temp_namespace, const char **atx_level)
{
const char *c;
const int mtm_tmp_len = strlen("mtm_tmp_");
int underscores = 0;
bool need_digit = true;
bool valid = true;
*atx_level = NULL;
if (strlen(temp_namespace) + strlen("_toast") + 1 > NAMEDATALEN)
valid = false;
else if(strncmp(temp_namespace, "mtm_tmp_", mtm_tmp_len) != 0)
valid = false;
for (c = temp_namespace+mtm_tmp_len; *c != 0 && valid; c++)
{
if (!need_digit && *c == '_')
{
underscores++;
if (underscores == 2)
*atx_level = c;
need_digit = true;
}
else if ((unsigned)*c - '0' <= '9' - '0')
need_digit = false;
else
valid = false;
}
if (need_digit || underscores < 1 || underscores > 2)
valid = false;
#ifndef PGPRO_EE
if (underscores == 2)
valid = false;
#endif
return valid;
}
Datum
mtm_set_temp_schema(PG_FUNCTION_ARGS)
{
char *temp_namespace = text_to_cstring(PG_GETARG_TEXT_P(0));
bool force = PG_NARGS() > 1 ? PG_GETARG_BOOL(1) : true;
char temp_toast_namespace[NAMEDATALEN] = {0};
Oid nsp_oid = InvalidOid;
Oid toast_nsp_oid = InvalidOid;
const char *atx_level_start = NULL;
#ifdef PGPRO_EE
char top_temp_namespace[NAMEDATALEN] = {0};
Oid top_nsp_oid = InvalidOid;
Oid top_toast_nsp_oid = InvalidOid;
#endif
if (!temp_schema_valid(temp_namespace, &atx_level_start))
mtm_log(ERROR, "mtm_set_temp_schema: wrong namespace name '%s'",
temp_namespace);
snprintf(temp_toast_namespace, NAMEDATALEN, "%s_toast", temp_namespace);
if (SearchSysCacheExists1(NAMESPACENAME, PointerGetDatum(temp_namespace)))
{
nsp_oid = get_namespace_oid(temp_namespace, false);
toast_nsp_oid = get_namespace_oid(temp_toast_namespace, false);
}
else if (force)
{
nsp_oid = NamespaceCreate(temp_namespace, BOOTSTRAP_SUPERUSERID, true);
toast_nsp_oid = NamespaceCreate(temp_toast_namespace, BOOTSTRAP_SUPERUSERID, true);
CommandCounterIncrement();
}
#ifdef PGPRO_EE
if (atx_level_start != NULL)
{
memcpy(top_temp_namespace, temp_namespace, atx_level_start - temp_namespace);
if (SearchSysCacheExists1(NAMESPACENAME, PointerGetDatum(top_temp_namespace)))
{
top_nsp_oid = get_namespace_oid(top_temp_namespace, false);
strlcat(top_temp_namespace, "_toast", NAMEDATALEN);
top_toast_nsp_oid = get_namespace_oid(top_temp_namespace, false);
}
}
SetTempNamespaceForMultimaster();
SetTempNamespaceStateEx(nsp_oid, toast_nsp_oid,
top_nsp_oid, top_toast_nsp_oid,
atx_level_start != NULL);
#else
SetTempNamespace(nsp_oid, toast_nsp_oid);
#endif
PG_RETURN_VOID();
}
/*****************************************************************************
*
* Guc handling
*
*****************************************************************************/
/* XXX: move to ShmemStart? */
static void
MtmGucInit(void)
{
HASHCTL hash_ctl;
MemoryContext oldcontext;
MemSet(&hash_ctl, 0, sizeof(hash_ctl));
hash_ctl.keysize = GUC_KEY_MAXLEN;
hash_ctl.entrysize = sizeof(MtmGucEntry);
hash_ctl.hcxt = TopMemoryContext;
MtmGucHash = hash_create("MtmGucHash",
MTM_GUC_HASHSIZE,
&hash_ctl,
HASH_ELEM | HASH_CONTEXT);
/*
* If current role is not equal to MtmDatabaseUser, than set it before any
* other GUC vars.
*
* XXX: try to avoid using MtmDatabaseUser somehow
*/
oldcontext = MemoryContextSwitchTo(TopMemoryContext);
/*
* XXX if (current_role && *current_role && strcmp(MtmDatabaseUser,
* current_role) != 0)
*/
MtmGucUpdate("session_authorization");
MemoryContextSwitchTo(oldcontext);
}
static void
MtmGucDiscard()
{
if (dlist_is_empty(&MtmGucList))
return;
dlist_init(&MtmGucList);
hash_destroy(MtmGucHash);
MtmGucHash = NULL;
}
static inline void
MtmGucUpdate(const char *key)
{
MtmGucEntry *hentry;
bool found;
if (!MtmGucHash)
MtmGucInit();
hentry = (MtmGucEntry *) hash_search(MtmGucHash, key, HASH_ENTER, &found);
if (found)
dlist_delete(&hentry->list_node);
dlist_push_tail(&MtmGucList, &hentry->list_node);
}
static inline void
MtmGucRemove(const char *key)
{
MtmGucEntry *hentry;
bool found;
if (!MtmGucHash)
MtmGucInit();
hentry = (MtmGucEntry *) hash_search(MtmGucHash, key, HASH_FIND, &found);
if (found)
{
dlist_delete(&hentry->list_node);
hash_search(MtmGucHash, key, HASH_REMOVE, NULL);
}
}
static void
MtmGucSet(VariableSetStmt *stmt, const char *queryStr)
{
MemoryContext oldcontext;
if (!MtmGucHash)
MtmGucInit();
oldcontext = MemoryContextSwitchTo(TopMemoryContext);
switch (stmt->kind)
{
case VAR_SET_VALUE:
MtmGucUpdate(stmt->name);
break;
case VAR_SET_DEFAULT:
MtmGucRemove(stmt->name);
break;
case VAR_RESET:
if (strcmp(stmt->name, "session_authorization") == 0)
MtmGucRemove("role");
MtmGucRemove(stmt->name);
break;
case VAR_RESET_ALL:
/* XXX: shouldn't we keep auth/role here? */
MtmGucDiscard();
break;
case VAR_SET_CURRENT:
case VAR_SET_MULTI:
break;
}
MemoryContextSwitchTo(oldcontext);
}
/*
* the bare comparison function for GUC names
*/
static int
_guc_name_compare(const char *namea, const char *nameb)
{
/*
* The temptation to use strcasecmp() here must be resisted, because the
* array ordering has to remain stable across setlocale() calls. So, build
* our own with a simple ASCII-only downcasing.
*/
while (*namea && *nameb)
{
char cha = *namea++;
char chb = *nameb++;
if (cha >= 'A' && cha <= 'Z')
cha += 'a' - 'A';
if (chb >= 'A' && chb <= 'Z')
chb += 'a' - 'A';
if (cha != chb)
return cha - chb;
}
if (*namea)
return 1; /* a is longer */
if (*nameb)
return -1; /* b is longer */
return 0;
}
static int
_var_name_cmp(const void *a, const void *b)
{
const struct config_generic *confa = *(struct config_generic *const *) a;
const struct config_generic *confb = *(struct config_generic *const *) b;
return _guc_name_compare(confa->name, confb->name);
}
static struct config_generic *
fing_guc_conf(const char *name)
{
int num;
struct config_generic **vars;
const char **key = &name;
struct config_generic **res;
num = GetNumConfigOptions();
vars = get_guc_variables();
res = (struct config_generic **) bsearch((void *) &key,
(void *) vars,
num, sizeof(struct config_generic *),
_var_name_cmp);
return res ? *res : NULL;
}
char *
MtmGucSerialize(void)
{
StringInfo serialized_gucs = makeStringInfo();
dlist_iter iter;
const char *search_path;
bool found;
Oid ceUserId = GetUserId();
Oid csUserId = GetSessionUserId();
bool useRole = is_member_of_role(csUserId, ceUserId);
if (!MtmGucHash)
MtmGucInit();
Assert(TempDropRegistered);
appendStringInfoString(serialized_gucs, "RESET session_authorization; ");
appendStringInfo(serialized_gucs, "select mtm.set_temp_schema('%s'); ", MtmTempSchema);
hash_search(MtmGucHash, "session_authorization", HASH_FIND, &found);
if (found)
{
MemoryContext oldcontext;
oldcontext = MemoryContextSwitchTo(TopMemoryContext);
hash_search(MtmGucHash, "role", HASH_FIND, &found);
if ((found) && (ceUserId == csUserId))
/*
* We need to do this because SET LOCAL return only WARNING if is
* used out of transaction block. DDL will be passed to another
* nodes and will set "role" variable at current node.
*/
MtmGucRemove("role");
else if ((!found) && (ceUserId != csUserId) && useRole)
/*
* We need to do this because SECURITY DEFINER changed current
* user value quietly.
*/
MtmGucUpdate("role");
MemoryContextSwitchTo(oldcontext);
}
dlist_foreach(iter, &MtmGucList)
{
MtmGucEntry *cur_entry = dlist_container(MtmGucEntry, list_node, iter.cur);
struct config_generic *gconf;
const char *gucValue;
if (strcmp(cur_entry->key, "search_path") == 0)
continue;
appendStringInfoString(serialized_gucs, "SET ");
appendStringInfoString(serialized_gucs, cur_entry->key);
appendStringInfoString(serialized_gucs, " TO ");
/*
* Current effective user can have more privileges than session user
* (increase in rights by SECURITY DEFINER, for example). In this case
* we need to set session authorization role in the current user
* value.
*/
if (strcmp(cur_entry->key, "session_authorization") == 0)
gucValue = GetUserNameFromId(useRole ? csUserId : ceUserId, false);
else
gucValue = GetConfigOption(cur_entry->key, false, true);
gconf = fing_guc_conf(cur_entry->key);
if (gconf && (gconf->vartype == PGC_STRING ||
gconf->vartype == PGC_ENUM ||
(gconf->flags & (GUC_UNIT_MEMORY | GUC_UNIT_TIME))))
{
appendStringInfoString(serialized_gucs, "'");
appendStringInfoString(serialized_gucs, gucValue);
appendStringInfoString(serialized_gucs, "'");
}
else
appendStringInfoString(serialized_gucs, gucValue);
appendStringInfoString(serialized_gucs, "; ");
}
/*
* Crutch for scheduler. It sets search_path through SetConfigOption() so
* our callback do not react on that.
*/
search_path = GetConfigOption("search_path", false, true);
if (strcmp(search_path, "\"\"") == 0 || strlen(search_path) == 0)
appendStringInfo(serialized_gucs, "SET search_path TO ''; ");
else
appendStringInfo(serialized_gucs, "SET search_path TO %s; ", search_path);
return serialized_gucs->data;
}
/*****************************************************************************
*
* Capture DDL statements and send them down to subscribers
*
*****************************************************************************/
/*
* if non-transactional, concurrent defines whether DDL must be executed in
* main receiver or concurrently in workers. Doesn't matter for
* transactional (it is executed in the context of xact).
*/
static void
MtmProcessDDLCommand(char const *queryString, bool transactional,
bool concurrent)
{
if (transactional)
{
char *gucCtx;
temp_schema_init();
gucCtx = MtmGucSerialize();
queryString = psprintf("%s %s", gucCtx, queryString);
/* Transactional DDL */
mtm_log(DDLStmtOutgoing, "sending DDL: %s", queryString);
LogLogicalMessage("D", queryString, strlen(queryString) + 1, true);
}
else
{
/* Concurrent DDL */
mtm_log(DDLStmtOutgoing, "sending non-tx %s DDL: %s",
queryString, concurrent ? "concurrent" : "non-concurrent");
XLogFlush(LogLogicalMessage(concurrent ? "C" : "V",
queryString, strlen(queryString) + 1, false));
}
}
static void
MtmFinishDDLCommand()
{
LogLogicalMessage("E", "", 1, true);
}
static void
MtmProcessUtility(PlannedStmt *pstmt, const char *queryString,
ProcessUtilityContext context, ParamListInfo params,
QueryEnvironment *queryEnv, DestReceiver *dest,
QueryCompletion *qc)
{
/*
* Quick exit if multimaster is not enabled.
* XXX it's better to do MtmIsEnabled here, but this needs cache access
* which requires live transaction, and suprisingly in ROLLBACK to x in
* enum.sql test we got here in TRANS_ABORT.
*/
if (Mtm->my_node_id == 0)
{
if (PreviousProcessUtilityHook != NULL)
{
PreviousProcessUtilityHook(pstmt, queryString,
context, params, queryEnv,
dest, qc);
}
else
{
standard_ProcessUtility(pstmt, queryString,
context, params, queryEnv,
dest, qc);
}
return;
}
if (MtmIsLogicalReceiver)
{
MtmProcessUtilityReceiver(pstmt, queryString, context, params,
queryEnv, dest, qc);
}
else
{
MtmProcessUtilitySender(pstmt, queryString, context, params,
queryEnv, dest, qc);
}
}
/*
* Process utility statements on receiver side.
*
* Some DDL isn't allowed to run inside transaction, so we are copying parse
* tree into MtmCapturedDDL and preventing it's execution by not calling
* standard_ProcessUtility() at the end of hook.
*
* Later MtmApplyDDLMessage() checks MtmCapturedDDL and executes it if something
* was caught.
*
* DDLApplyInProgress ensures that this hook will only called for DDL
* originated from MtmApplyDDLMessage(). In other cases of DDL happening in
* receiver (e.g calling DDL from trigger) this hook does nothing.
*/
static void
MtmProcessUtilityReceiver(PlannedStmt *pstmt, const char *queryString,
ProcessUtilityContext context, ParamListInfo params,
QueryEnvironment *queryEnv, DestReceiver *dest,
QueryCompletion *qc)
{
Node *parsetree = pstmt->utilityStmt;
/* catch only DDL produced by SPI in MtmApplyDDLMessage() */
if (DDLApplyInProgress)
{
MemoryContext oldMemContext = MemoryContextSwitchTo(MtmApplyContext);
bool captured = false;
mtm_log(DDLProcessingTrace,
"MtmProcessUtilityReceiver: tag=%s, context=%d, issubtrans=%d, statement=%s",
GetCommandTagName(CreateCommandTag(parsetree)),
context, IsSubTransaction(), queryString);
Assert(oldMemContext != MtmApplyContext);
Assert(MtmApplyContext != NULL);
/* copy parsetrees of interest to MtmCapturedDDL */
switch (nodeTag(parsetree))
{
case T_CreateTableSpaceStmt:
case T_DropTableSpaceStmt:
Assert(MtmCapturedDDL == NULL);
MtmCapturedDDL = copyObject(parsetree);
captured = true;
break;
case T_IndexStmt:
{
IndexStmt *stmt = (IndexStmt *) parsetree;
if (stmt->concurrent)
{
Assert(MtmCapturedDDL == NULL);
MtmCapturedDDL = (Node *) copyObject(stmt);
captured = true;
}
break;
}
#ifdef PGPROEE
case T_PartitionStmt:
{
PartitionStmt *stmt = (PartitionStmt *) parsetree;
if (stmt->concurrent)
{
Assert(MtmCapturedDDL == NULL);
MtmCapturedDDL = (Node *) copyObject(stmt);
captured = true;
}
break;
}
#endif
case T_AlterEnumStmt:
{
AlterEnumStmt *stmt = (AlterEnumStmt *) parsetree;
Assert(MtmCapturedDDL == NULL);
MtmCapturedDDL = (Node *) copyObject(stmt);
captured = true;
break;
}
case T_DropStmt:
{
DropStmt *stmt = (DropStmt *) parsetree;
if (stmt->removeType == OBJECT_INDEX && stmt->concurrent)
{
Assert(MtmCapturedDDL == NULL);
MtmCapturedDDL = (Node *) copyObject(stmt);
captured = true;
}
/*
* Make it possible to drop functions which were not
* replicated
*/
else if (stmt->removeType == OBJECT_FUNCTION)
{
stmt->missing_ok = true;
}
break;
}
/* disable function body check at replica */
case T_CreateFunctionStmt:
check_function_bodies = false;
break;
case T_CreateSeqStmt:
{
CreateSeqStmt *stmt = (CreateSeqStmt *) parsetree;
if (!MtmVolksWagenMode)
stmt->options = AdjustCreateSequence(stmt->options);
break;
}
default:
break;
}
MemoryContextSwitchTo(oldMemContext);
/* prevent captured statement from execution */
if (captured)
{
mtm_log(DDLProcessingTrace, "MtmCapturedDDL = %s",
GetCommandTagName(CreateCommandTag((Node *) MtmCapturedDDL)));
return;
}
}
if (PreviousProcessUtilityHook != NULL)
{
PreviousProcessUtilityHook(pstmt, queryString,
context, params, queryEnv,
dest, qc);
}
else
{
standard_ProcessUtility(pstmt, queryString,
context, params, queryEnv,
dest, qc);
}
}
static void
MtmProcessUtilitySender(PlannedStmt *pstmt, const char *queryString,
ProcessUtilityContext context, ParamListInfo params,
QueryEnvironment *queryEnv, DestReceiver *dest,
QueryCompletion *qc)
{
bool skipCommand = false;
bool executed = false;
Node *parsetree = pstmt->utilityStmt;
int stmt_start = pstmt->stmt_location > 0 ? pstmt->stmt_location : 0;
int stmt_len = pstmt->stmt_len > 0 ? pstmt->stmt_len : strlen(queryString + stmt_start);
char *stmt_string = palloc(stmt_len + 1);
bool isTopLevel = (context == PROCESS_UTILITY_TOPLEVEL);
/*
* Generate schema name and send logical message saying to destroy the
* schema on peers on backend exit only if this command has a chance of
* using temp objects remotely.
*/
#define SkipCommand(skip) \
{ \
if (!skip) \
temp_schema_init(); \
skipCommand = skip; \
}
strncpy(stmt_string, queryString + stmt_start, stmt_len);
stmt_string[stmt_len] = 0;
mtm_log(DDLProcessingTrace,
"MtmProcessUtilitySender tag=%d, context=%d, issubtrans=%d, statement=%s",
nodeTag(parsetree), context, IsSubTransaction(), stmt_string);
switch (nodeTag(parsetree))
{
case T_TransactionStmt:
{
TransactionStmt *stmt = (TransactionStmt *) parsetree;
/*
* hack: if we are going to commit/prepare but our transaction
* block is already aborted, we'd better just fast pass this
* over to the core code before checking whether mtm state
* allows to commit (and generally starting complicated commit
* procedure). We expect PrepareTransactionBlock not to fail
* after this. Hackish, as it repurposes
* TransactionBlockStatusCode.
*/
if ((stmt->kind == TRANS_STMT_COMMIT ||
stmt->kind == TRANS_STMT_PREPARE) &&
TransactionBlockStatusCode() == 'E')
{
skipCommand = true;
break;
}
switch (stmt->kind)
{
case TRANS_STMT_COMMIT:
if (stmt->chain)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
MTM_ERRMSG("COMMIT AND CHAIN is not supported")));
if (MtmTwoPhaseCommit())