forked from apache/cloudberry
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCTranslatorQueryToDXL.cpp
More file actions
5006 lines (4343 loc) · 157 KB
/
CTranslatorQueryToDXL.cpp
File metadata and controls
5006 lines (4343 loc) · 157 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
//---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2011 EMC Corp.
//
// @filename:
// CTranslatorQueryToDXL.cpp
//
// @doc:
// Implementation of the methods used to translate a query into DXL tree.
// All translator methods allocate memory in the provided memory pool, and
// the caller is responsible for freeing it
//
// @test:
//
//---------------------------------------------------------------------------
extern "C" {
#include "postgres.h"
#include "access/sysattr.h"
#include "catalog/heap.h"
#include "catalog/pg_class.h"
#include "nodes/makefuncs.h"
#include "nodes/parsenodes.h"
#include "nodes/plannodes.h"
#include "optimizer/walkers.h"
#include "utils/guc.h"
#include "utils/rel.h"
}
#include "gpos/base.h"
#include "gpos/common/CAutoTimer.h"
#include "gpopt/base/CUtils.h"
#include "gpopt/gpdbwrappers.h"
#include "gpopt/mdcache/CMDAccessor.h"
#include "gpopt/translate/CCTEListEntry.h"
#include "gpopt/translate/CQueryMutators.h"
#include "gpopt/translate/CTranslatorDXLToPlStmt.h"
#include "gpopt/translate/CTranslatorQueryToDXL.h"
#include "gpopt/translate/CTranslatorRelcacheToDXL.h"
#include "gpopt/translate/CTranslatorUtils.h"
#include "naucrates/dxl/CDXLUtils.h"
#include "naucrates/dxl/operators/CDXLDatumInt4.h"
#include "naucrates/dxl/operators/CDXLDatumInt8.h"
#include "naucrates/dxl/operators/CDXLLogicalCTAS.h"
#include "naucrates/dxl/operators/CDXLLogicalCTEAnchor.h"
#include "naucrates/dxl/operators/CDXLLogicalCTEConsumer.h"
#include "naucrates/dxl/operators/CDXLLogicalCTEProducer.h"
#include "naucrates/dxl/operators/CDXLLogicalConstTable.h"
#include "naucrates/dxl/operators/CDXLLogicalDelete.h"
#include "naucrates/dxl/operators/CDXLLogicalForeignGet.h"
#include "naucrates/dxl/operators/CDXLLogicalGet.h"
#include "naucrates/dxl/operators/CDXLLogicalGroupBy.h"
#include "naucrates/dxl/operators/CDXLLogicalInsert.h"
#include "naucrates/dxl/operators/CDXLLogicalJoin.h"
#include "naucrates/dxl/operators/CDXLLogicalLimit.h"
#include "naucrates/dxl/operators/CDXLLogicalProject.h"
#include "naucrates/dxl/operators/CDXLLogicalSelect.h"
#include "naucrates/dxl/operators/CDXLLogicalUpdate.h"
#include "naucrates/dxl/operators/CDXLLogicalWindow.h"
#include "naucrates/dxl/operators/CDXLScalarBooleanTest.h"
#include "naucrates/dxl/operators/CDXLScalarLimitCount.h"
#include "naucrates/dxl/operators/CDXLScalarLimitOffset.h"
#include "naucrates/dxl/operators/CDXLScalarProjElem.h"
#include "naucrates/dxl/operators/CDXLScalarProjList.h"
#include "naucrates/dxl/operators/CDXLScalarSortCol.h"
#include "naucrates/dxl/operators/CDXLScalarSortColList.h"
#include "naucrates/dxl/operators/CDXLScalarWindowFrameEdge.h"
#include "naucrates/dxl/operators/CDXLScalarWindowRef.h"
#include "naucrates/dxl/xml/dxltokens.h"
#include "naucrates/exception.h"
#include "naucrates/md/CMDIdGPDBCtas.h"
#include "naucrates/md/CMDTypeBoolGPDB.h"
#include "naucrates/md/IMDAggregate.h"
#include "naucrates/md/IMDScalarOp.h"
#include "naucrates/md/IMDTypeBool.h"
#include "naucrates/md/IMDTypeInt4.h"
#include "naucrates/md/IMDTypeInt8.h"
#include "naucrates/traceflags/traceflags.h"
using namespace gpdxl;
using namespace gpos;
using namespace gpopt;
using namespace gpnaucrates;
using namespace gpmd;
extern bool optimizer_enable_ctas;
extern bool optimizer_enable_dml;
extern bool optimizer_enable_dml_constraints;
extern bool optimizer_enable_replicated_table;
extern bool optimizer_enable_multiple_distinct_aggs;
// OIDs of variants of LEAD window function
static const OID lead_func_oids[] = {
7011, 7074, 7075, 7310, 7312, 7314, 7316, 7318, 7320, 7322, 7324, 7326,
7328, 7330, 7332, 7334, 7336, 7338, 7340, 7342, 7344, 7346, 7348, 7350,
7352, 7354, 7356, 7358, 7360, 7362, 7364, 7366, 7368, 7370, 7372, 7374,
7376, 7378, 7380, 7382, 7384, 7386, 7388, 7390, 7392, 7394, 7396, 7398,
7400, 7402, 7404, 7406, 7408, 7410, 7412, 7414, 7416, 7418, 7420, 7422,
7424, 7426, 7428, 7430, 7432, 7434, 7436, 7438, 7440, 7442, 7444, 7446,
7448, 7450, 7452, 7454, 7456, 7458, 7460, 7462, 7464, 7466, 7468, 7470,
7472, 7474, 7476, 7478, 7480, 7482, 7484, 7486, 7488, 7214, 7215, 7216,
7220, 7222, 7224, 7244, 7246, 7248, 7260, 7262, 7264};
// OIDs of variants of LAG window function
static const OID lag_func_oids[] = {
7675, 7491, 7493, 7495, 7497, 7499, 7501, 7503, 7505, 7507, 7509, 7511,
7513, 7515, 7517, 7519, 7521, 7523, 7525, 7527, 7529, 7531, 7533, 7535,
7537, 7539, 7541, 7543, 7545, 7547, 7549, 7551, 7553, 7555, 7557, 7559,
7561, 7563, 7565, 7567, 7569, 7571, 7573, 7575, 7577, 7579, 7581, 7583,
7585, 7587, 7589, 7591, 7593, 7595, 7597, 7599, 7601, 7603, 7605, 7607,
7609, 7611, 7613, 7615, 7617, 7619, 7621, 7623, 7625, 7627, 7629, 7631,
7633, 7635, 7637, 7639, 7641, 7643, 7645, 7647, 7649, 7651, 7653, 7655,
7657, 7659, 7661, 7663, 7665, 7667, 7669, 7671, 7673, 7211, 7212, 7213,
7226, 7228, 7230, 7250, 7252, 7254, 7266, 7268, 7270};
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::CTranslatorQueryToDXL
//
// @doc:
// Private constructor. This is used when starting on the
// top-level Query, and also when recursing into a subquery.
//
//---------------------------------------------------------------------------
CTranslatorQueryToDXL::CTranslatorQueryToDXL(
CContextQueryToDXL *context, CMDAccessor *md_accessor,
const CMappingVarColId *var_colid_mapping, Query *query, ULONG query_level,
BOOL is_top_query_dml, HMUlCTEListEntry *query_level_to_cte_map)
: m_context(context),
m_mp(context->m_mp),
m_sysid(IMDId::EmdidGeneral, GPMD_GPDB_SYSID),
m_md_accessor(md_accessor),
m_query_level(query_level),
m_is_top_query_dml(is_top_query_dml),
m_is_ctas_query(false),
m_query_level_to_cte_map(nullptr),
m_dxl_query_output_cols(nullptr),
m_dxl_cte_producers(nullptr),
m_cteid_at_current_query_level_map(nullptr)
{
GPOS_ASSERT(nullptr != query);
CheckSupportedCmdType(query);
m_query_id = m_context->GetNextQueryId();
CheckRangeTable(query);
// GPDB_94_MERGE_FIXME: WITH CHECK OPTION views are not supported yet.
// I'm not sure what would be needed to support them; maybe need to
// just pass through the withCheckOptions to the ModifyTable / DML node?
if (query->withCheckOptions)
{
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("View with WITH CHECK OPTION"));
}
// Initialize the map that stores gpdb att to optimizer col mapping.
// If this is a subquery, make a copy of the parent's mapping, otherwise
// initialize a new, empty, mapping.
if (var_colid_mapping)
{
m_var_to_colid_map = var_colid_mapping->CopyMapColId(m_mp);
}
else
{
m_var_to_colid_map = GPOS_NEW(m_mp) CMappingVarColId(m_mp);
}
m_query_level_to_cte_map = GPOS_NEW(m_mp) HMUlCTEListEntry(m_mp);
m_dxl_cte_producers = GPOS_NEW(m_mp) CDXLNodeArray(m_mp);
m_cteid_at_current_query_level_map = GPOS_NEW(m_mp) UlongBoolHashMap(m_mp);
if (nullptr != query_level_to_cte_map)
{
HMIterUlCTEListEntry cte_list_hashmap_iter(query_level_to_cte_map);
while (cte_list_hashmap_iter.Advance())
{
ULONG cte_query_level = *(cte_list_hashmap_iter.Key());
CCTEListEntry *cte_list_entry =
const_cast<CCTEListEntry *>(cte_list_hashmap_iter.Value());
// CTE's that have been defined before the m_query_level
// should only be inserted into the hash map
// For example:
// WITH ab as (SELECT a as a, b as b from foo)
// SELECT *
// FROM
// (WITH aEq10 as (SELECT b from ab ab1 where ab1.a = 10)
// SELECT *
// FROM (WITH aEq20 as (SELECT b from ab ab2 where ab2.a = 20)
// SELECT * FROM aEq10 WHERE b > (SELECT min(b) from aEq20)
// ) dtInner
// ) dtOuter
// When translating the from expression containing "aEq10" in the derived table "dtInner"
// we have already seen three CTE namely: "ab", "aEq10" and "aEq20". BUT when we expand aEq10
// in the dt1, we should only have access of CTE's defined prior to its level namely "ab".
if (cte_query_level < query_level && nullptr != cte_list_entry)
{
cte_list_entry->AddRef();
BOOL is_res GPOS_ASSERTS_ONLY =
m_query_level_to_cte_map->Insert(
GPOS_NEW(m_mp) ULONG(cte_query_level), cte_list_entry);
GPOS_ASSERT(is_res);
}
}
}
// check if the query has any unsupported node types
CheckUnsupportedNodeTypes(query);
// check if the query has SIRV functions in the targetlist without a FROM clause
CheckSirvFuncsWithoutFromClause(query);
// first normalize the query
m_query =
CQueryMutators::NormalizeQuery(m_mp, m_md_accessor, query, query_level);
if (nullptr != m_query->cteList)
{
ConstructCTEProducerList(m_query->cteList, query_level);
}
m_scalar_translator = GPOS_NEW(m_mp)
CTranslatorScalarToDXL(m_context, m_md_accessor, m_query_level,
m_query_level_to_cte_map, m_dxl_cte_producers);
}
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::QueryToDXLInstance
//
// @doc:
// Factory function. Creates a new CTranslatorQueryToDXL object
// for translating the given top-level query.
//
//---------------------------------------------------------------------------
CTranslatorQueryToDXL *
CTranslatorQueryToDXL::QueryToDXLInstance(CMemoryPool *mp,
CMDAccessor *md_accessor,
Query *query)
{
CContextQueryToDXL *context = GPOS_NEW(mp) CContextQueryToDXL(mp);
return GPOS_NEW(context->m_mp)
CTranslatorQueryToDXL(context, md_accessor,
nullptr, // var_colid_mapping,
query,
0, // query_level
false, // is_top_query_dml
nullptr // query_level_to_cte_map
);
}
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::~CTranslatorQueryToDXL
//
// @doc:
// Dtor
//
//---------------------------------------------------------------------------
CTranslatorQueryToDXL::~CTranslatorQueryToDXL()
{
GPOS_DELETE(m_scalar_translator);
GPOS_DELETE(m_var_to_colid_map);
gpdb::GPDBFree(m_query);
m_query_level_to_cte_map->Release();
m_dxl_cte_producers->Release();
m_cteid_at_current_query_level_map->Release();
CRefCount::SafeRelease(m_dxl_query_output_cols);
if (m_query_level == 0)
{
GPOS_DELETE(m_context);
}
}
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::CheckUnsupportedNodeTypes
//
// @doc:
// Check for unsupported node types, and throws an exception when found
//
//---------------------------------------------------------------------------
void
CTranslatorQueryToDXL::CheckUnsupportedNodeTypes(Query *query)
{
static const SUnsupportedFeature unsupported_features[] = {
{T_RowExpr, GPOS_WSZ_LIT("ROW EXPRESSION")},
{T_RowCompareExpr, GPOS_WSZ_LIT("ROW COMPARE")},
{T_FieldStore, GPOS_WSZ_LIT("FIELDSTORE")},
{T_CoerceToDomainValue, GPOS_WSZ_LIT("COERCETODOMAINVALUE")},
{T_GroupId, GPOS_WSZ_LIT("GROUPID")},
{T_CurrentOfExpr, GPOS_WSZ_LIT("CURRENT OF")},
};
List *unsupported_list = NIL;
for (ULONG ul = 0; ul < GPOS_ARRAY_SIZE(unsupported_features); ul++)
{
unsupported_list = gpdb::LAppendInt(unsupported_list,
unsupported_features[ul].node_tag);
}
INT unsupported_node = gpdb::FindNodes((Node *) query, unsupported_list);
gpdb::GPDBFree(unsupported_list);
if (0 <= unsupported_node)
{
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
unsupported_features[unsupported_node].m_feature_name);
}
// GPDB_91_MERGE_FIXME: collation
INT non_default_collation = gpdb::CheckCollation((Node *) query);
if (0 < non_default_collation)
{
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("Non-default collation"));
}
// ORCA does not support amcanorderbyop (KNN ordered index scans).
// Fall back to the PostgreSQL planner for queries whose ORDER BY
// contains an ordering operator (e.g., <-> for distance).
if (gpdb::HasOrderByOrderingOp(query))
{
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("ORDER BY with ordering operator (amcanorderbyop)"));
}
}
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::CheckSirvFuncsWithoutFromClause
//
// @doc:
// Check for SIRV functions in the target list without a FROM clause, and
// throw an exception when found
//
//---------------------------------------------------------------------------
void
CTranslatorQueryToDXL::CheckSirvFuncsWithoutFromClause(Query *query)
{
// if there is a FROM clause or if target list is empty, look no further
if ((nullptr != query->jointree &&
0 < gpdb::ListLength(query->jointree->fromlist)) ||
NIL == query->targetList)
{
return;
}
// see if we have SIRV functions in the target list
if (HasSirvFunctions((Node *) query->targetList))
{
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("SIRV functions"));
}
}
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::HasSirvFunctions
//
// @doc:
// Check for SIRV functions in the tree rooted at the given node
//
//---------------------------------------------------------------------------
BOOL
CTranslatorQueryToDXL::HasSirvFunctions(Node *node) const
{
GPOS_ASSERT(nullptr != node);
List *function_list = gpdb::ExtractNodesExpression(
node, T_FuncExpr, true /*descendIntoSubqueries*/);
ListCell *lc = nullptr;
BOOL has_sirv = false;
ForEach(lc, function_list)
{
FuncExpr *func_expr = (FuncExpr *) lfirst(lc);
if (CTranslatorUtils::IsSirvFunc(m_mp, m_md_accessor,
func_expr->funcid))
{
has_sirv = true;
break;
}
}
gpdb::ListFree(function_list);
return has_sirv;
}
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::CheckSupportedCmdType
//
// @doc:
// Check for supported command types, throws an exception when command
// type not yet supported
//---------------------------------------------------------------------------
void
CTranslatorQueryToDXL::CheckSupportedCmdType(Query *query)
{
if (nullptr != query->utilityStmt)
{
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("UTILITY command"));
}
if (CMD_SELECT == query->commandType)
{
// GPDB_92_MERGE_FIXME: CTAS is a UTILITY statement after upstream
// refactoring commit 9dbf2b7d . We are temporarily *always* falling
// back. Detect CTAS harder when we get back to it.
if (!optimizer_enable_ctas &&
query->parentStmtType == PARENTSTMTTYPE_CTAS)
{
GPOS_RAISE(
gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT(
"CTAS. Set optimizer_enable_ctas to on to enable CTAS with GPORCA"));
}
if (query->parentStmtType == PARENTSTMTTYPE_COPY)
{
GPOS_RAISE(
gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT(
"COPY. Copy select statement to file on segment is not supported with GPORCA"));
}
if (query->parentStmtType == PARENTSTMTTYPE_REFRESH_MATVIEW)
{
GPOS_RAISE(
gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("Refresh matview is not supported with GPORCA"));
}
// supported: regular select or CTAS when it is enabled
return;
}
static const SCmdNameElem unsupported_commands[] = {
{CMD_UTILITY, GPOS_WSZ_LIT("UTILITY command")}};
const ULONG length = GPOS_ARRAY_SIZE(unsupported_commands);
for (ULONG ul = 0; ul < length; ul++)
{
SCmdNameElem mapelem = unsupported_commands[ul];
if (mapelem.m_cmd_type == query->commandType)
{
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
mapelem.m_cmd_name);
}
}
}
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::CheckRangeTable
//
// @doc:
// Check for supported stuff in range table, throws an exception
// if there is something that is not yet supported
//---------------------------------------------------------------------------
void
CTranslatorQueryToDXL::CheckRangeTable(Query *query)
{
ListCell *lc;
ForEach(lc, query->rtable)
{
RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
if (rte->security_barrier)
{
GPOS_ASSERT_FIXME(RTE_SUBQUERY == rte->rtekind);
// otherwise ORCA most likely pushes potentially leaky filters down
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("views with security_barrier ON"));
}
// In a rewritten parse tree
//
// [1] When hasRowSecurity=false and security_quals are not
// present in an rte, means that the relations present in a
// query don't have row level security enabled.
//
// [2] When hasRowSecurity=true and security_quals are present
// in an rte, means that the relations present in a query have
// row level security enabled.
//
// [3] When hasRowSecurity=true and security_quals are not
// present in an rte, means that the relations present in
// a query have row level security enabled but the query is
// executed by the owner of the relation.
//
// [4] When hasRowSecurity=false and security_quals are
// present in an rte example: A view with security barrier
// enabled and the view contains a relation with rules.
// Example query is below
//
// ```SQL
// CREATE TABLE foo(id int PRIMARY KEY, data text, deleted boolean);
// CREATE RULE foo_del_rule AS ON DELETE TO foo DO INSTEAD UPDATE foo SET deleted = true WHERE id = old.id;
// CREATE VIEW rw_view1 WITH (security_barrier=true) AS SELECT id, data FROM foo WHERE NOT deleted;
// DELETE FROM rw_view1 WHERE id = 1;
// ```
// ORCA will fallback to planner for this case [4].
if (!query->hasRowSecurity && nullptr != rte->securityQuals)
{
GPOS_RAISE(
gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT(
"Security quals present in RTE without row level security enabled"));
}
// ORCA will fallback to planner if row level security is
// enabled for a relation and the security quals contain
// sublinks.
if (query->hasRowSecurity && query->hasSubLinks &&
0 < gpdb::ListLength(rte->securityQuals) &&
CheckSublinkInSecurityQuals((Node *) rte->securityQuals, nullptr))
{
GPOS_RAISE(
gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT(
"Query has row level security enabled and security quals contain sublinks"));
}
if (rte->tablesample)
{
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("TABLESAMPLE in the FROM clause"));
}
if (rte->relkind == RELKIND_PARTITIONED_TABLE && query->hasRowSecurity && GPOS_FTRACE(EopttraceDisableDynamicTableScan)) {
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("ORCA not support row-level security if dynamic table scan is disabled."));
}
}
}
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::CheckSublinkInSecurityQuals
//
// @doc:
// When row level security is enabled we add the security quals
// while translating the table scans from DXL To Planned Statement.
// If the security quals consists of SUBLINKS then those queries
// will not have been planned as we add them at the end during
// translation. So falling back to planner for such cases. This walker
// is used to find if we have any sublinks present in the security quals.
//
//---------------------------------------------------------------------------
BOOL
CTranslatorQueryToDXL::CheckSublinkInSecurityQuals(Node *node, void *context)
{
if (nullptr == node)
{
return false;
}
if (IsA(node, SubLink))
{
return true;
}
return gpdb::WalkExpressionTree(
node, (bool (*)(Node *, void *)) CTranslatorQueryToDXL::CheckSublinkInSecurityQuals,
context);
}
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::GetQueryOutputCols
//
// @doc:
// Return the list of query output columns
//
//---------------------------------------------------------------------------
CDXLNodeArray *
CTranslatorQueryToDXL::GetQueryOutputCols() const
{
return m_dxl_query_output_cols;
}
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::GetCTEs
//
// @doc:
// Return the list of CTEs
//
//---------------------------------------------------------------------------
CDXLNodeArray *
CTranslatorQueryToDXL::GetCTEs() const
{
return m_dxl_cte_producers;
}
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::TranslateSelectQueryToDXL
//
// @doc:
// Translates a Query into a DXL tree. The function allocates memory in
// the translator memory pool, and caller is responsible for freeing it.
//
//---------------------------------------------------------------------------
CDXLNode *
CTranslatorQueryToDXL::TranslateSelectQueryToDXL()
{
// The parsed query contains an RTE for the view, which is maintained all the way through planned statement.
// This entries is annotated as requiring SELECT permissions for the current user.
// In Orca, we only keep range table entries for the base tables in the planned statement, but not for the view itself.
// Since permissions are only checked during ExecutorStart, we lose track of the permissions required for the view and the select goes through successfully.
// We therefore need to check permissions before we go into optimization for all RTEs, including the ones not explicitly referred in the query, e.g. views.
CTranslatorUtils::CheckRTEPermissions(m_query->rtable);
if (m_query->hasForUpdate)
{
int rt_len = gpdb::ListLength(m_query->rtable);
for (int i = 0; i < rt_len; i++)
{
const RangeTblEntry *rte =
(RangeTblEntry *) gpdb::ListNth(m_query->rtable, i);
if (rte->relkind == 'f' && rte->rellockmode == ExclusiveLock)
{
GPOS_RAISE(gpdxl::ExmaDXL,
gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("Locking clause on foreign table"));
}
}
}
// RETURNING is not supported yet.
if (m_query->returningList)
{
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("RETURNING clause"));
}
// ON CONFLICT is not supported yet.
if (m_query->onConflict)
{
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("ON CONFLICT clause"));
}
if (m_query->limitOption == LIMIT_OPTION_WITH_TIES)
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("LIMIT WITH TIES clause"));
CDXLNode *child_dxlnode = nullptr;
IntToUlongMap *sort_group_attno_to_colid_mapping =
GPOS_NEW(m_mp) IntToUlongMap(m_mp);
IntToUlongMap *output_attno_to_colid_mapping =
GPOS_NEW(m_mp) IntToUlongMap(m_mp);
// construct CTEAnchor operators for the CTEs defined at the top level
CDXLNode *dxl_cte_anchor_top = nullptr;
CDXLNode *dxl_cte_anchor_bottom = nullptr;
ConstructCTEAnchors(m_dxl_cte_producers, &dxl_cte_anchor_top,
&dxl_cte_anchor_bottom);
GPOS_ASSERT_IMP(
m_dxl_cte_producers == nullptr || 0 < m_dxl_cte_producers->Size(),
nullptr != dxl_cte_anchor_top && nullptr != dxl_cte_anchor_bottom);
GPOS_ASSERT_IMP(nullptr != m_query->setOperations,
0 == gpdb::ListLength(m_query->windowClause));
if (nullptr != m_query->setOperations)
{
List *target_list = m_query->targetList;
// translate set operations
child_dxlnode = TranslateSetOpToDXL(m_query->setOperations, target_list,
output_attno_to_colid_mapping);
CDXLLogicalSetOp *dxlop =
CDXLLogicalSetOp::Cast(child_dxlnode->GetOperator());
const CDXLColDescrArray *dxl_col_descr_array =
dxlop->GetDXLColumnDescrArray();
ListCell *lc = nullptr;
ULONG resno = 1;
ForEach(lc, target_list)
{
TargetEntry *target_entry = (TargetEntry *) lfirst(lc);
if (0 < target_entry->ressortgroupref)
{
ULONG colid = ((*dxl_col_descr_array)[resno - 1])->Id();
AddSortingGroupingColumn(
target_entry, sort_group_attno_to_colid_mapping, colid);
}
resno++;
}
}
else if (0 != gpdb::ListLength(
m_query->windowClause)) // translate window clauses
{
CDXLNode *dxlnode = TranslateFromExprToDXL(m_query->jointree);
GPOS_ASSERT(nullptr == m_query->groupClause);
GPOS_ASSERT(nullptr == m_query->groupingSets);
child_dxlnode = TranslateWindowToDXL(
dxlnode, m_query->targetList, m_query->windowClause,
m_query->sortClause, sort_group_attno_to_colid_mapping,
output_attno_to_colid_mapping);
}
else
{
child_dxlnode = TranslateGroupingSets(
m_query->jointree, m_query->targetList, m_query->groupClause,
m_query->groupingSets, m_query->groupDistinct, m_query->hasAggs,
sort_group_attno_to_colid_mapping, output_attno_to_colid_mapping);
}
// translate limit clause
CDXLNode *limit_dxlnode = TranslateLimitToDXLGroupBy(
m_query->sortClause, m_query->limitCount, m_query->limitOffset,
child_dxlnode, sort_group_attno_to_colid_mapping);
if (nullptr == m_query->targetList)
{
m_dxl_query_output_cols = GPOS_NEW(m_mp) CDXLNodeArray(m_mp);
}
else
{
m_dxl_query_output_cols = CreateDXLOutputCols(
m_query->targetList, output_attno_to_colid_mapping);
}
// cleanup
CRefCount::SafeRelease(sort_group_attno_to_colid_mapping);
output_attno_to_colid_mapping->Release();
// add CTE anchors if needed
CDXLNode *result_dxlnode = limit_dxlnode;
if (nullptr != dxl_cte_anchor_top)
{
GPOS_ASSERT(nullptr != dxl_cte_anchor_bottom);
dxl_cte_anchor_bottom->AddChild(result_dxlnode);
result_dxlnode = dxl_cte_anchor_top;
}
return result_dxlnode;
}
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::TranslateSelectProjectJoinToDXL
//
// @doc:
// Construct a DXL SPJ tree from the given query parts
//
//---------------------------------------------------------------------------
CDXLNode *
CTranslatorQueryToDXL::TranslateSelectProjectJoinToDXL(
List *target_list, FromExpr *from_expr,
IntToUlongMap *sort_group_attno_to_colid_mapping,
IntToUlongMap *output_attno_to_colid_mapping, List *group_clause)
{
CDXLNode *join_tree_dxlnode = TranslateFromExprToDXL(from_expr);
// translate target list entries into a logical project
return TranslateTargetListToDXLProject(
target_list, join_tree_dxlnode, sort_group_attno_to_colid_mapping,
output_attno_to_colid_mapping, group_clause);
}
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::TranslateSelectProjectJoinForGrpSetsToDXL
//
// @doc:
// Construct a DXL SPJ tree from the given query parts, and keep variables
// appearing in aggregates in the project list
//
//---------------------------------------------------------------------------
CDXLNode *
CTranslatorQueryToDXL::TranslateSelectProjectJoinForGrpSetsToDXL(
List *target_list, FromExpr *from_expr,
IntToUlongMap *sort_group_attno_to_colid_mapping,
IntToUlongMap *output_attno_to_colid_mapping, List *group_clause)
{
CDXLNode *join_tree_dxlnode = TranslateFromExprToDXL(from_expr);
// translate target list entries into a logical project
return TranslateTargetListToDXLProject(
target_list, join_tree_dxlnode, sort_group_attno_to_colid_mapping,
output_attno_to_colid_mapping, group_clause,
true /*is_expand_aggref_expr*/);
}
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::TranslateQueryToDXL
//
// @doc:
// Main driver
//
//---------------------------------------------------------------------------
CDXLNode *
CTranslatorQueryToDXL::TranslateQueryToDXL()
{
CAutoTimer at("\n[OPT]: Query To DXL Translation Time",
GPOS_FTRACE(EopttracePrintOptimizationStatistics));
switch (m_query->commandType)
{
case CMD_SELECT:
if (m_query->parentStmtType == PARENTSTMTTYPE_NONE)
{
return TranslateSelectQueryToDXL();
}
else
{
return TranslateCTASToDXL();
}
case CMD_INSERT:
return TranslateInsertQueryToDXL();
case CMD_DELETE:
return TranslateDeleteQueryToDXL();
case CMD_UPDATE:
return TranslateUpdateQueryToDXL();
default:
GPOS_ASSERT(!"Statement type not supported");
return nullptr;
}
}
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::TranslateInsertQueryToDXL
//
// @doc:
// Translate an insert stmt
//
//---------------------------------------------------------------------------
CDXLNode *
CTranslatorQueryToDXL::TranslateInsertQueryToDXL()
{
GPOS_ASSERT(CMD_INSERT == m_query->commandType);
GPOS_ASSERT(0 < m_query->resultRelation);
if (!optimizer_enable_dml)
{
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("DML not enabled"));
}
if (gp_random_insert_segments > 0)
{
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("limited insert segments not supported"));
}
CDXLNode *query_dxlnode = TranslateSelectQueryToDXL();
const RangeTblEntry *rte = (RangeTblEntry *) gpdb::ListNth(
m_query->rtable, m_query->resultRelation - 1);
if (rte->relkind == 'f')
{
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("Inserts with foreign tables"));
}
CDXLTableDescr *table_descr = CTranslatorUtils::GetTableDescr(
m_mp, m_md_accessor, m_context->m_colid_counter, rte, m_query_id,
&m_context->m_has_distributed_tables);
const IMDRelation *md_rel = m_md_accessor->RetrieveRel(table_descr->MDId());
BOOL rel_has_constraints = CTranslatorUtils::RelHasConstraints(md_rel);
if (!optimizer_enable_dml_constraints && rel_has_constraints)
{
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT("INSERT with constraints"));
}
BOOL contains_foreign_parts =
CTranslatorUtils::RelContainsForeignPartitions(md_rel, m_md_accessor);
if (contains_foreign_parts)
{
// Partitioned tables with external/foreign partitions
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiQuery2DXLUnsupportedFeature,
GPOS_WSZ_LIT(
"Insert with External/foreign partition storage types"));
}
// make note of the operator classes used in the distribution key
NoteDistributionPolicyOpclasses(rte);
const ULONG num_table_columns =
CTranslatorUtils::GetNumNonSystemColumns(md_rel);
const ULONG target_list_length = gpdb::ListLength(m_query->targetList);
GPOS_ASSERT(num_table_columns >= target_list_length);
GPOS_ASSERT(target_list_length == m_dxl_query_output_cols->Size());
CDXLNode *project_list_dxlnode = nullptr;
const ULONG num_system_cols = md_rel->ColumnCount() - num_table_columns;
const ULONG num_non_dropped_cols =
md_rel->NonDroppedColsCount() - num_system_cols;
if (num_non_dropped_cols > target_list_length)
{
// missing target list entries
project_list_dxlnode = GPOS_NEW(m_mp)
CDXLNode(m_mp, GPOS_NEW(m_mp) CDXLScalarProjList(m_mp));
}
ULongPtrArray *source_array = GPOS_NEW(m_mp) ULongPtrArray(m_mp);
ULONG target_list_pos = 0;
for (ULONG ul = 0; ul < num_table_columns; ul++)
{
const IMDColumn *mdcol = md_rel->GetMdCol(ul);
GPOS_ASSERT(!mdcol->IsSystemColumn());
if (mdcol->IsDropped())
{
continue;
}
if (target_list_pos < target_list_length)
{
INT attno = mdcol->AttrNum();
TargetEntry *target_entry = (TargetEntry *) gpdb::ListNth(
m_query->targetList, target_list_pos);
AttrNumber resno = target_entry->resno;
if (attno == resno)
{
CDXLNode *dxl_column =
(*m_dxl_query_output_cols)[target_list_pos];
CDXLScalarIdent *dxl_ident =
CDXLScalarIdent::Cast(dxl_column->GetOperator());
source_array->Append(
GPOS_NEW(m_mp) ULONG(dxl_ident->GetDXLColRef()->Id()));
target_list_pos++;
continue;
}
}
// target entry corresponding to the tables column not found, therefore
// add a project element with null value scalar child
CDXLNode *project_elem_dxlnode =
CTranslatorUtils::CreateDXLProjElemConstNULL(
m_mp, m_md_accessor, m_context->m_colid_counter, mdcol);
ULONG colid =
CDXLScalarProjElem::Cast(project_elem_dxlnode->GetOperator())->Id();
project_list_dxlnode->AddChild(project_elem_dxlnode);
source_array->Append(GPOS_NEW(m_mp) ULONG(colid));
}
CDXLLogicalInsert *insert_dxlnode =
GPOS_NEW(m_mp) CDXLLogicalInsert(m_mp, table_descr, source_array);
if (nullptr != project_list_dxlnode)
{
GPOS_ASSERT(0 < project_list_dxlnode->Arity());
CDXLNode *project_dxlnode = GPOS_NEW(m_mp)
CDXLNode(m_mp, GPOS_NEW(m_mp) CDXLLogicalProject(m_mp));
project_dxlnode->AddChild(project_list_dxlnode);
project_dxlnode->AddChild(query_dxlnode);
query_dxlnode = project_dxlnode;
}
return GPOS_NEW(m_mp) CDXLNode(m_mp, insert_dxlnode, query_dxlnode);
}
//---------------------------------------------------------------------------
// @function:
// CTranslatorQueryToDXL::TranslateCTASToDXL
//
// @doc:
// Translate a CTAS
//
//---------------------------------------------------------------------------
CDXLNode *
CTranslatorQueryToDXL::TranslateCTASToDXL()
{
GPOS_ASSERT(CMD_SELECT == m_query->commandType);
const char *const relname = "FAKE_CTAS_RELNAME";
m_is_ctas_query = true;
CDXLNode *query_dxlnode = TranslateSelectQueryToDXL();
CMDName *md_relname = CDXLUtils::CreateMDNameFromCharArray(m_mp, relname);