-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathexecMain.c
More file actions
4374 lines (3886 loc) · 129 KB
/
execMain.c
File metadata and controls
4374 lines (3886 loc) · 129 KB
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
/*-------------------------------------------------------------------------
*
* execMain.c
* top level executor interface routines
*
* INTERFACE ROUTINES
* ExecutorStart()
* ExecutorRun()
* ExecutorFinish()
* ExecutorEnd()
*
* These four procedures are the external interface to the executor.
* In each case, the query descriptor is required as an argument.
*
* ExecutorStart must be called at the beginning of execution of any
* query plan and ExecutorEnd must always be called at the end of
* execution of a plan (unless it is aborted due to error).
*
* ExecutorRun accepts direction and count arguments that specify whether
* the plan is to be executed forwards, backwards, and for how many tuples.
* In some cases ExecutorRun may be called multiple times to process all
* the tuples for a plan. It is also acceptable to stop short of executing
* the whole plan (but only if it is a SELECT).
*
* ExecutorFinish must be called after the final ExecutorRun call and
* before ExecutorEnd. This can be omitted only in case of EXPLAIN,
* which should also omit ExecutorRun.
*
* Portions Copyright (c) 2005-2010, Greenplum inc
* Portions Copyright (c) 2012-Present VMware, Inc. or its affiliates.
* Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/executor/execMain.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "pgstat.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/tableam.h"
#include "access/transam.h"
#include "access/xact.h"
#include "catalog/namespace.h"
#include "catalog/pg_publication.h"
#include "catalog/storage_directory_table.h"
#include "commands/matview.h"
#include "commands/tablespace.h"
#include "commands/trigger.h"
#include "executor/execdebug.h"
#include "executor/nodeModifyTable.h"
#include "executor/nodeSubplan.h"
#include "foreign/fdwapi.h"
#include "jit/jit.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/plannodes.h"
#include "parser/parsetree.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "tcop/utility.h"
#include "utils/acl.h"
#include "utils/backend_status.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/partcache.h"
#include "utils/rls.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
#include "utils/metrics_utils.h"
#include "utils/queryenvironment.h"
#include "utils/ps_status.h"
#include "utils/typcache.h"
#include "utils/workfile_mgr.h"
#include "utils/faultinjector.h"
#include "utils/resource_manager.h"
#include "utils/cgroup.h"
#include "catalog/pg_statistic.h"
#include "catalog/pg_class.h"
#include "tcop/tcopprot.h"
#include "catalog/pg_tablespace.h"
#include "catalog/catalog.h"
#include "catalog/gp_matview_aux.h"
#include "catalog/oid_dispatch.h"
#include "catalog/pg_directory_table.h"
#include "catalog/pg_type.h"
#include "commands/copy.h"
#include "commands/createas.h"
#include "executor/execUtils.h"
#include "executor/instrument.h"
#include "executor/nodeSubplan.h"
#include "foreign/fdwapi.h"
#include "libpq/pqformat.h"
#include "cdb/cdbdisp_query.h"
#include "cdb/cdbdispatchresult.h"
#include "cdb/cdbexplain.h" /* cdbexplain_sendExecStats() */
#include "cdb/cdbplan.h"
#include "cdb/cdbsubplan.h"
#include "cdb/cdbvars.h"
#include "cdb/ml_ipc.h"
#include "cdb/cdbmotion.h"
#include "cdb/cdbtm.h"
#include "cdb/cdboidsync.h"
#include "cdb/cdbllize.h"
#include "cdb/memquota.h"
#include "cdb/cdbtargeteddispatch.h"
#include "cdb/cdbutil.h"
#include "cdb/cdbendpoint.h"
#define IS_PARALLEL_RETRIEVE_CURSOR(queryDesc) (queryDesc->ddesc && \
queryDesc->ddesc->parallelCursorName && \
strlen(queryDesc->ddesc->parallelCursorName) > 0)
/* Hooks for plugins to get control in ExecutorStart/Run/Finish/End */
ExecutorStart_hook_type ExecutorStart_hook = NULL;
ExecutorRun_hook_type ExecutorRun_hook = NULL;
ExecutorFinish_hook_type ExecutorFinish_hook = NULL;
ExecutorEnd_hook_type ExecutorEnd_hook = NULL;
/* Hook for plugin to get control in ExecCheckRTPerms() */
ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL;
/*
* Greenplum specific code:
* Greenplum introduces auto_stats for a long time, please refer to
* https://groups.google.com/a/greenplum.org/g/gpdb-dev/c/bAyw2KBP6yE/m/hmoWikrPAgAJ
* for details and decision of auto_stats.
*
* auto_stats() now is invoked at the following 7 places:
* 1. ProcessQuery()
* 2. _SPI_pquery()
* 3. postquel_end()
* 4. ATExecExpandTableCTAS()
* 5. ATExecSetDistributedBy()
* 6. DoCopy()
* 7. ExecCreateTableAs()
*
* Previously, Place 2, 3 is hard-coded as inside function,
* Place 1, 4~7 is hard-coded as not-inside function.
* Place 4~7 does not cover the case that COPY or CTAS
* is called inside procedure language.
*
* Since in future auto_stats will be removed, for now let's
* just to do some simple fix instead of big refactor.
*
* To correctly pass the inFunction parameter for auto_stats()
* at Place 4~7 we introduce executor_run_nesting_level to mark
* if the program is already under ExecutorRun(). Place 4~7 is
* directly taken as Utility and will not call ExecutorRun() if
* they are not inside procedure language. This skill is like
* the extension `auto_explain`.
*
* For Place 1~3, the context is clear we do not need to check
* executor_run_nesting_level.
*/
static int executor_run_nesting_level = 0;
/* decls for local routines only used within this module */
static void InitPlan(QueryDesc *queryDesc, int eflags);
static void CheckValidRowMarkRel(Relation rel, RowMarkType markType);
static void ExecPostprocessPlan(EState *estate);
static void ExecEndPlan(PlanState *planstate, EState *estate);
static void ExecutePlan(EState *estate, PlanState *planstate,
bool use_parallel_mode,
CmdType operation,
bool sendTuples,
uint64 numberTuples,
ScanDirection direction,
DestReceiver *dest,
bool execute_once);
static bool ExecCheckRTEPermsModified(Oid relOid, Oid userid,
Bitmapset *modifiedCols,
AclMode requiredPerms);
static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
static char *ExecBuildSlotValueDescription(Oid reloid,
TupleTableSlot *slot,
TupleDesc tupdesc,
Bitmapset *modifiedCols,
int maxfieldlen);
static void EvalPlanQualStart(EPQState *epqstate, Plan *planTree);
static void AdjustReplicatedTableCounts(EState *estate);
static void
MaintainMaterializedViewStatus(QueryDesc *queryDesc, CmdType operation);
/* end of local decls */
/* ----------------------------------------------------------------
* ExecutorStart
*
* This routine must be called at the beginning of any execution of any
* query plan
*
* Takes a QueryDesc previously created by CreateQueryDesc (which is separate
* only because some places use QueryDescs for utility commands). The tupDesc
* field of the QueryDesc is filled in to describe the tuples that will be
* returned, and the internal fields (estate and planstate) are set up.
*
* eflags contains flag bits as described in executor.h.
*
* NB: the CurrentMemoryContext when this is called will become the parent
* of the per-query context used for this Executor invocation.
*
* We provide a function hook variable that lets loadable plugins
* get control when ExecutorStart is called. Such a plugin would
* normally call standard_ExecutorStart().
*
* MPP: In here we take care of setting up all the necessary items that
* will be needed to service the query, such as setting up interconnect,
* and dispatching the query. Any other items in the future
* must be added here.
*
* ----------------------------------------------------------------
*/
void
ExecutorStart(QueryDesc *queryDesc, int eflags)
{
/*
* In some cases (e.g. an EXECUTE statement) a query execution will skip
* parse analysis, which means that the query_id won't be reported. Note
* that it's harmless to report the query_id multiple time, as the call
* will be ignored if the top level query_id has already been reported.
*/
pgstat_report_query_id(queryDesc->plannedstmt->queryId, false);
if (ExecutorStart_hook)
(*ExecutorStart_hook) (queryDesc, eflags);
else
standard_ExecutorStart(queryDesc, eflags);
}
void
standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
{
EState *estate;
MemoryContext oldcontext;
GpExecIdentity exec_identity;
bool shouldDispatch;
bool needDtx;
List *volatile toplevelOidCache = NIL;
/* sanity checks: queryDesc must not be started already */
Assert(queryDesc != NULL);
Assert(queryDesc->estate == NULL);
Assert(queryDesc->plannedstmt != NULL);
Assert(queryDesc->plannedstmt->intoPolicy == NULL ||
GpPolicyIsPartitioned(queryDesc->plannedstmt->intoPolicy) ||
GpPolicyIsReplicated(queryDesc->plannedstmt->intoPolicy));
/* GPDB hook for collecting query info */
if (query_info_collect_hook)
(*query_info_collect_hook)(METRICS_QUERY_START, queryDesc);
if (Gp_role == GP_ROLE_DISPATCH)
{
if (!IsResManagerMemoryPolicyNone() &&
LogResManagerMemory())
{
elog(GP_RESMANAGER_MEMORY_LOG_LEVEL, "query requested %.0fKB of memory",
(double) queryDesc->plannedstmt->query_mem / 1024.0);
}
if (queryDesc->plannedstmt->query_mem > 0)
{
PG_TRY();
{
switch (*gp_resmanager_memory_policy)
{
case RESMANAGER_MEMORY_POLICY_AUTO:
PolicyAutoAssignOperatorMemoryKB(queryDesc->plannedstmt,
queryDesc->plannedstmt->query_mem);
break;
case RESMANAGER_MEMORY_POLICY_EAGER_FREE:
PolicyEagerFreeAssignOperatorMemoryKB(queryDesc->plannedstmt,
queryDesc->plannedstmt->query_mem);
break;
default:
Assert(IsResManagerMemoryPolicyNone());
break;
}
}
PG_CATCH();
{
/* GPDB hook for collecting query info */
if (query_info_collect_hook)
(*query_info_collect_hook)(QueryCancelCleanup ? METRICS_QUERY_CANCELED : METRICS_QUERY_ERROR, queryDesc);
PG_RE_THROW();
}
PG_END_TRY();
}
}
/*
* If the transaction is read-only, we need to check if any writes are
* planned to non-temporary tables. EXPLAIN is considered read-only.
*
* Don't allow writes in parallel mode. Supporting UPDATE and DELETE
* would require (a) storing the combo CID hash in shared memory, rather
* than synchronizing it just once at the start of parallelism, and (b) an
* alternative to heap_update()'s reliance on xmax for mutual exclusion.
* INSERT may have no such troubles, but we forbid it to simplify the
* checks.
*
* We have lower-level defenses in CommandCounterIncrement and elsewhere
* against performing unsafe operations in parallel mode, but this gives a
* more user-friendly error message.
*
* In GPDB, we must call ExecCheckXactReadOnly() in the QD even if the
* transaction is not read-only, because ExecCheckXactReadOnly() also
* determines if two-phase commit is needed.
*/
if ((XactReadOnly || IsInParallelMode() || Gp_role == GP_ROLE_DISPATCH) &&
!(eflags & EXEC_FLAG_EXPLAIN_ONLY))
{
PG_TRY();
{
ExecCheckXactReadOnly(queryDesc->plannedstmt);
}
PG_CATCH();
{
/* GPDB hook for collecting query info */
if (query_info_collect_hook)
(*query_info_collect_hook)(QueryCancelCleanup ? METRICS_QUERY_CANCELED : METRICS_QUERY_ERROR, queryDesc);
PG_RE_THROW();
}
PG_END_TRY();
}
/*
* Build EState, switch into per-query memory context for startup.
*/
estate = CreateExecutorState();
queryDesc->estate = estate;
oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
/**
* Attached the plannedstmt from queryDesc
*/
estate->es_plannedstmt = queryDesc->plannedstmt;
/*
* Fill in external parameters, if any, from queryDesc; and allocate
* workspace for internal parameters
*/
estate->es_param_list_info = queryDesc->params;
if (queryDesc->plannedstmt->paramExecTypes != NIL)
{
int nParamExec;
nParamExec = list_length(queryDesc->plannedstmt->paramExecTypes);
estate->es_param_exec_vals = (ParamExecData *)
palloc0(nParamExec * sizeof(ParamExecData));
}
/* We now require all callers to provide sourceText */
Assert(queryDesc->sourceText != NULL);
estate->es_sourceText = queryDesc->sourceText;
/*
* Fill in the query environment, if any, from queryDesc.
*/
if (queryDesc->ddesc && queryDesc->ddesc->namedRelList)
{
if (queryDesc->queryEnv == NULL)
queryDesc->queryEnv = create_queryEnv();
/* Update environment */
AddPreassignedENR(queryDesc->queryEnv, queryDesc->ddesc->namedRelList);
}
estate->es_queryEnv = queryDesc->queryEnv;
/*
* If non-read-only query, set the command ID to mark output tuples with
*/
switch (queryDesc->operation)
{
case CMD_SELECT:
/*
* SELECT FOR [KEY] UPDATE/SHARE and modifying CTEs need to mark
* tuples
*/
if (queryDesc->plannedstmt->rowMarks != NIL ||
queryDesc->plannedstmt->hasModifyingCTE)
{
estate->es_output_cid = GetCurrentCommandId(true);
}
/*
* A SELECT without modifying CTEs can't possibly queue triggers,
* so force skip-triggers mode. This is just a marginal efficiency
* hack, since AfterTriggerBeginQuery/AfterTriggerEndQuery aren't
* all that expensive, but we might as well do it.
*/
if (!queryDesc->plannedstmt->hasModifyingCTE)
eflags |= EXEC_FLAG_SKIP_TRIGGERS;
break;
case CMD_INSERT:
case CMD_DELETE:
case CMD_UPDATE:
estate->es_output_cid = GetCurrentCommandId(true);
break;
default:
elog(ERROR, "unrecognized operation code: %d",
(int) queryDesc->operation);
break;
}
/*
* Copy other important information into the EState
*/
estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
estate->es_top_eflags = eflags;
estate->es_instrument = queryDesc->instrument_options;
estate->es_jit_flags = queryDesc->plannedstmt->jitFlags;
estate->showstatctx = queryDesc->showstatctx;
/*
* Shared input info is needed when ROLE_EXECUTE or sequential plan
*/
estate->es_sharenode = NIL;
/*
* Handling of the Slice table depends on context.
*/
if (Gp_role == GP_ROLE_DISPATCH)
{
/* Set up the slice table. */
SliceTable *sliceTable;
sliceTable = InitSliceTable(estate, queryDesc->plannedstmt);
estate->es_sliceTable = sliceTable;
if (sliceTable->slices[0].gangType != GANGTYPE_UNALLOCATED ||
sliceTable->hasMotions)
{
if (queryDesc->ddesc == NULL)
{
queryDesc->ddesc = makeNode(QueryDispatchDesc);;
queryDesc->ddesc->useChangedAOOpts = true;
}
/* Pass EXPLAIN ANALYZE flag to qExecs. */
estate->es_sliceTable->instrument_options = queryDesc->instrument_options;
/* set our global sliceid variable for elog. */
currentSliceId = LocallyExecutingSliceIndex(estate);
/* InitPlan() will acquire locks by walking the entire plan
* tree -- we'd like to avoid acquiring the locks until
* *after* we've set up the interconnect */
if (estate->es_sliceTable->hasMotions)
estate->motionlayer_context = createMotionLayerState(queryDesc->plannedstmt->numSlices - 1);
shouldDispatch = !(eflags & EXEC_FLAG_EXPLAIN_ONLY);
}
else
{
/* QD-only query, no dispatching required */
shouldDispatch = false;
}
/*
* If this is CREATE TABLE AS ... WITH NO DATA, there's no need
* need to actually execute the plan.
*/
if (queryDesc->plannedstmt->intoClause &&
queryDesc->plannedstmt->intoClause->skipData)
shouldDispatch = false;
}
else if (Gp_role == GP_ROLE_EXECUTE)
{
QueryDispatchDesc *ddesc = queryDesc->ddesc;
shouldDispatch = false;
/* qDisp should have sent us a slice table via MPPEXEC */
if (ddesc && ddesc->sliceTable != NULL)
{
SliceTable *sliceTable;
ExecSlice *slice;
sliceTable = ddesc->sliceTable;
Assert(IsA(sliceTable, SliceTable));
slice = &sliceTable->slices[sliceTable->localSlice];
estate->es_sliceTable = sliceTable;
estate->es_cursorPositions = ddesc->cursorPositions;
estate->currentSliceId = slice->rootIndex;
/* set our global sliceid variable for elog. */
currentSliceId = LocallyExecutingSliceIndex(estate);
/* Should we collect statistics for EXPLAIN ANALYZE? */
estate->es_instrument = sliceTable->instrument_options;
queryDesc->instrument_options = sliceTable->instrument_options;
/* InitPlan() will acquire locks by walking the entire plan
* tree -- we'd like to avoid acquiring the locks until
* *after* we've set up the interconnect */
if (estate->es_sliceTable->hasMotions)
{
estate->motionlayer_context = createMotionLayerState(queryDesc->plannedstmt->numSlices - 1);
PG_TRY();
{
/*
* Initialize the motion layer for this query.
*/
Assert(!estate->interconnect_context);
CurrentMotionIPCLayer->SetupInterconnect(estate);
Assert(estate->interconnect_context);
UpdateMotionExpectedReceivers(estate->motionlayer_context, estate->es_sliceTable);
SIMPLE_FAULT_INJECTOR("qe_got_snapshot_and_interconnect");
}
PG_CATCH();
{
mppExecutorCleanup(queryDesc);
PG_RE_THROW();
}
PG_END_TRY();
}
}
else
{
/* local query in QE. */
}
}
else
shouldDispatch = false;
/*
* We don't eliminate aliens if we don't have an MPP plan
* or we are executing on master.
*
* TODO: eliminate aliens even on master, if not EXPLAIN ANALYZE
*/
estate->eliminateAliens = execute_pruned_plan && estate->es_sliceTable && estate->es_sliceTable->hasMotions && (Gp_role == GP_ROLE_EXECUTE);
/*
* Set up an AFTER-trigger statement context, unless told not to, or
* unless it's EXPLAIN-only mode (when ExecutorFinish won't be called).
*/
if (!(eflags & (EXEC_FLAG_SKIP_TRIGGERS | EXEC_FLAG_EXPLAIN_ONLY)))
AfterTriggerBeginQuery();
/*
* Initialize the plan state tree
*
* If the interconnect has been set up; we need to catch any
* errors to shut it down -- so we have to wrap InitPlan in a PG_TRY() block.
*/
PG_TRY();
{
/*
* Initialize the plan state tree
*/
Assert(CurrentMemoryContext == estate->es_query_cxt);
InitPlan(queryDesc, eflags);
Assert(queryDesc->planstate);
#ifdef USE_ASSERT_CHECKING
AssertSliceTableIsValid(estate->es_sliceTable);
#endif
if (Debug_print_slice_table && Gp_role == GP_ROLE_DISPATCH)
elog_node_display(DEBUG3, "slice table", estate->es_sliceTable, true);
/*
* If we're running as a QE and there's a slice table in our queryDesc,
* then we need to finish the EState setup we prepared for back in
* CdbExecQuery.
*/
if (Gp_role == GP_ROLE_EXECUTE && estate->es_sliceTable != NULL)
{
MotionState *motionstate = NULL;
/*
* Note that, at this point on a QE, the estate is setup (based on the
* slice table transmitted from the QD via MPPEXEC) so that fields
* es_sliceTable, cur_root_idx and es_cur_slice_idx are correct for
* the QE.
*
* If responsible for a non-root slice, arrange to enter the plan at the
* slice's sending Motion node rather than at the top.
*/
if (LocallyExecutingSliceIndex(estate) != RootSliceIndex(estate))
{
motionstate = getMotionState(queryDesc->planstate, LocallyExecutingSliceIndex(estate));
Assert(motionstate != NULL && IsA(motionstate, MotionState));
}
if (Debug_print_slice_table)
elog_node_display(DEBUG3, "slice table", estate->es_sliceTable, true);
if (gp_log_interconnect >= GPVARS_VERBOSITY_DEBUG)
elog(DEBUG1, "seg%d executing slice%d under root slice%d",
GpIdentity.segindex,
LocallyExecutingSliceIndex(estate),
RootSliceIndex(estate));
}
/*
* if in dispatch mode, time to serialize plan and query
* trees, and fire off cdb_exec command to each of the qexecs
*/
if (shouldDispatch)
{
/*
* MPP-2869: preprocess_initplans() may
* dispatch. (interacted with MPP-2859, which caused an
* initPlan to do a write which should have happened in
* main body of query) We need to call
* ExecutorSaysTransactionDoesWrites() before any dispatch
* work for this query.
*/
needDtx = ExecutorSaysTransactionDoesWrites();
if (needDtx)
setupDtxTransaction();
/*
* Aviod dispatching OIDs for InitPlan.
*
* CTAS will first define relation in QD, and generate the OIDs,
* and then dispatch with these OIDs to QEs.
* QEs store these OIDs in a static variable and delete the one
* used to create table.
*
* If CTAS's query contains initplan, when we invoke
* preprocess_initplan to dispatch initplans, if with
* queryDesc->ddesc->oidAssignments be set, these OIDs are
* also dispatched to QEs.
*
* For details please see github issue https://github.com/greenplum-db/gpdb/issues/10760
*/
if (queryDesc->ddesc != NULL)
{
queryDesc->ddesc->sliceTable = estate->es_sliceTable;
FillQueryDispatchDesc(estate->es_queryEnv, queryDesc->ddesc);
/*
* For CTAS querys that contain initplan, we need to copy a new oid dispatch list,
* since the preprocess_initplan will start a subtransaction, and if it's rollbacked,
* the memory context of 'Oid dispatch context' will be reset, which will cause invalid
* list reference during the serialization of dispatch_oids when dispatching plan.
*/
toplevelOidCache = copyObject(GetAssignedOidsForDispatch());
}
/*
* First, pre-execute any initPlan subplans.
*/
if (list_length(queryDesc->plannedstmt->paramExecTypes) > 0)
preprocess_initplans(queryDesc);
if (toplevelOidCache != NIL)
{
queryDesc->ddesc->oidAssignments = toplevelOidCache;
}
/*
* This call returns after launching the threads that send the
* plan to the appropriate segdbs. It does not wait for them to
* finish unless an error is detected before all slices have been
* dispatched.
*
* Main plan is parallel, send plan to it.
*/
if (estate->es_sliceTable->slices[0].gangType != GANGTYPE_UNALLOCATED ||
estate->es_sliceTable->slices[0].children)
{
CdbDispatchPlan(queryDesc,
estate->es_param_exec_vals,
needDtx, true);
}
if (toplevelOidCache != NIL)
{
list_free(toplevelOidCache);
toplevelOidCache = NIL;
}
}
/*
* Get executor identity (who does the executor serve). we can assume
* Forward scan direction for now just for retrieving the identity.
*/
if (!(eflags & EXEC_FLAG_EXPLAIN_ONLY))
exec_identity = getGpExecIdentity(queryDesc, ForwardScanDirection, estate);
else
exec_identity = GP_IGNORE;
/*
* If we have no slice to execute in this process, mark currentSliceId as
* invalid.
*/
if (exec_identity == GP_IGNORE)
{
estate->currentSliceId = -1;
currentSliceId = -1;
}
#ifdef USE_ASSERT_CHECKING
/* non-root on QE */
if (exec_identity == GP_NON_ROOT_ON_QE)
{
MotionState *motionState = getMotionState(queryDesc->planstate, LocallyExecutingSliceIndex(estate));
Assert(motionState);
Assert(IsA(motionState->ps.plan, Motion));
}
else
#endif
if (exec_identity == GP_ROOT_SLICE)
{
/* Run a root slice. */
if (queryDesc->planstate != NULL &&
estate->es_sliceTable &&
estate->es_sliceTable->slices[0].gangType == GANGTYPE_UNALLOCATED &&
estate->es_sliceTable->slices[0].children &&
!estate->es_interconnect_is_setup)
{
Assert(!estate->interconnect_context);
CurrentMotionIPCLayer->SetupInterconnect(estate);
Assert(estate->interconnect_context);
UpdateMotionExpectedReceivers(estate->motionlayer_context, estate->es_sliceTable);
}
}
else if (exec_identity != GP_IGNORE)
{
/* should never happen */
Assert(!"unsupported parallel execution strategy");
}
if(estate->es_interconnect_is_setup)
Assert(estate->interconnect_context != NULL);
}
PG_CATCH();
{
if (toplevelOidCache != NIL)
{
list_free(toplevelOidCache);
toplevelOidCache = NIL;
}
mppExecutorCleanup(queryDesc);
PG_RE_THROW();
}
PG_END_TRY();
if (DEBUG1 >= log_min_messages)
{
char msec_str[32];
switch (check_log_duration(msec_str, false))
{
case 1:
case 2:
ereport(LOG, (errmsg("duration to ExecutorStart end: %s ms", msec_str)));
break;
}
}
MemoryContextSwitchTo(oldcontext);
}
/* ----------------------------------------------------------------
* ExecutorRun
*
* This is the main routine of the executor module. It accepts
* the query descriptor from the traffic cop and executes the
* query plan.
*
* ExecutorStart must have been called already.
*
* If direction is NoMovementScanDirection then nothing is done
* except to start up/shut down the destination. Otherwise,
* we retrieve up to 'count' tuples in the specified direction.
*
* Note: count = 0 is interpreted as no portal limit, i.e., run to
* completion. Also note that the count limit is only applied to
* retrieved tuples, not for instance to those inserted/updated/deleted
* by a ModifyTable plan node.
*
* There is no return value, but output tuples (if any) are sent to
* the destination receiver specified in the QueryDesc; and the number
* of tuples processed at the top level can be found in
* estate->es_processed.
*
* We provide a function hook variable that lets loadable plugins
* get control when ExecutorRun is called. Such a plugin would
* normally call standard_ExecutorRun().
*
* MPP: In here we must ensure to only run the plan and not call
* any setup/teardown items (unless in a CATCH block).
*
* ----------------------------------------------------------------
*/
void
ExecutorRun(QueryDesc *queryDesc,
ScanDirection direction, uint64 count,
bool execute_once)
{
/*
* Greenplum specific code:
* auto_stats() needs to know if it is inside procedure call so
* we maintain executor_run_nesting_level here. See detailed comments
* at the definition of the static variable executor_run_nesting_level.
*/
executor_run_nesting_level++;
PG_TRY();
{
if (ExecutorRun_hook)
(*ExecutorRun_hook) (queryDesc, direction, count, execute_once);
else
standard_ExecutorRun(queryDesc, direction, count, execute_once);
executor_run_nesting_level--;
}
PG_CATCH();
{
executor_run_nesting_level--;
PG_RE_THROW();
}
PG_END_TRY();
}
void
standard_ExecutorRun(QueryDesc *queryDesc,
ScanDirection direction, uint64 count, bool execute_once)
{
EState *estate;
CmdType operation;
DestReceiver *dest;
bool sendTuples;
MemoryContext oldcontext;
bool endpointCreated = false;
uint64 es_processed = 0;
/*
* NOTE: Any local vars that are set in the PG_TRY block and examined in the
* PG_CATCH block should be declared 'volatile'. (setjmp shenanigans)
*/
ExecSlice *currentSlice;
GpExecIdentity exec_identity;
bool amIParallel = false;
/* sanity checks */
Assert(queryDesc != NULL);
estate = queryDesc->estate;
Assert(estate != NULL);
Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
/*
* Switch into per-query memory context
*/
oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
/* Allow instrumentation of Executor overall runtime */
if (queryDesc->totaltime)
InstrStartNode(queryDesc->totaltime);
/*
* CDB: Update global slice id for log messages.
*/
currentSlice = getCurrentSlice(estate, LocallyExecutingSliceIndex(estate));
if (currentSlice)
{
if (Gp_role == GP_ROLE_EXECUTE ||
sliceRunsOnQD(currentSlice))
{
currentSliceId = currentSlice->sliceIndex;
amIParallel = currentSlice->useMppParallelMode;
}
}
/*
* extract information from the query descriptor and the query feature.
*/
operation = queryDesc->operation;
dest = queryDesc->dest;
/*
* startup tuple receiver, if we will be emitting tuples
*/
estate->es_processed = 0;
sendTuples = (queryDesc->tupDesc != NULL &&
(operation == CMD_SELECT ||
queryDesc->plannedstmt->hasReturning));
if (sendTuples)
dest->rStartup(dest, operation, queryDesc->tupDesc);
/*
* run plan
*/
if (!ScanDirectionIsNoMovement(direction))
{
if (execute_once && queryDesc->already_executed)
elog(ERROR, "can't re-execute query flagged for single execution");
queryDesc->already_executed = true;
}
/*
* Need a try/catch block here so that if an ereport is called from
* within ExecutePlan, we can clean up by calling CdbCheckDispatchResult.
* This cleans up the asynchronous commands running through the threads launched from
* CdbDispatchCommand.
*/
PG_TRY();
{
/*
* Run the plan locally. There are three ways;
*
* 1. Do nothing
* 2. Run a root slice
* 3. Run a non-root slice on a QE.
*
* Here we decide what is our identity -- root slice, non-root
* on QE or other (in which case we do nothing), and then run
* the plan if required. For more information see
* getGpExecIdentity() in execUtils.
*/
exec_identity = getGpExecIdentity(queryDesc, direction, estate);
if (exec_identity == GP_IGNORE)
{
/* do nothing */
estate->es_got_eos = true;
}
else if (exec_identity == GP_NON_ROOT_ON_QE)
{
/*
* Run a non-root slice on a QE.
*
* Since the top Plan node is a (Sending) Motion, run the plan
* forward to completion. The plan won't return tuples locally
* (tuples go out over the interconnect), so the destination is
* uninteresting. The command type should be SELECT, however, to
* avoid other sorts of DML processing..
*
* This is the center of slice plan activity -- here we arrange to
* blunder into the middle of the plan rather than entering at the
* root.
*/
MotionState *motionState = getMotionState(queryDesc->planstate, LocallyExecutingSliceIndex(estate));
Assert(motionState);
ExecutePlan(estate,
(PlanState *) motionState,
amIParallel,
CMD_SELECT,
sendTuples,
0,
ForwardScanDirection,
dest,
execute_once);
}
else if (exec_identity == GP_ROOT_SLICE)
{
DestReceiver *endpointDest;
/*
* When run a root slice, and it is a PARALLEL RETRIEVE CURSOR, it means
* QD become the end point for connection. It is true, for
* instance, SELECT * FROM foo LIMIT 10, and the result should
* go out from QD.
*
* For the scenario: endpoint on QE, the query plan is changed,
* the root slice also exists on QE.
*/
if (IS_PARALLEL_RETRIEVE_CURSOR(queryDesc))
{
SetupEndpointExecState(queryDesc->tupDesc,
queryDesc->ddesc->parallelCursorName,
operation,
&endpointDest);