-
Notifications
You must be signed in to change notification settings - Fork 37
/
hdfs_fdw.c
3429 lines (2990 loc) · 99.8 KB
/
hdfs_fdw.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
/*-------------------------------------------------------------------------
*
* hdfs_fdw.c
* Foreign-data wrapper for remote Hadoop servers
*
* Portions Copyright (c) 2012-2019, PostgreSQL Global Development Group
* Portions Copyright (c) 2004-2024, EnterpriseDB Corporation.
*
* IDENTIFICATION
* hdfs_fdw.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "access/xact.h"
#include "catalog/pg_type.h"
#include "commands/explain.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "hdfs_fdw.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/planmain.h"
#include "optimizer/optimizer.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/tlist.h"
#include "parser/parsetree.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/selfuncs.h"
#include "utils/typcache.h"
PG_MODULE_MAGIC;
/* Default CPU cost to start up a foreign query. */
#define DEFAULT_FDW_STARTUP_COST 100000.0
/* Default CPU cost to process 1 row */
#define DEFAULT_FDW_TUPLE_COST 1000.0
/*
* In PG 9.5.1 the number will be 90501,
* our version is 2.3.2 so number will be 20302
*/
#define CODE_VERSION 20302
/*
* The number of rows in a foreign relation are estimated to be so less that
* an in-memory sort on those many rows wouldn't cost noticeably higher than
* the underlying scan. Hence for now, cost sorts same as underlying scans.
*/
#define DEFAULT_HDFS_SORT_MULTIPLIER 1
/* GUC variables. */
static bool enable_join_pushdown = true;
static bool enable_aggregate_pushdown = true;
static bool enable_order_by_pushdown = false;
static bool enable_limit_pushdown = true;
/*
* Indexes of FDW-private information stored in fdw_private lists.
*
* These items are indexed with the enum hdfsFdwScanPrivateIndex, so an item
* can be fetched with list_nth(). For example, to get the SELECT statement:
* sql = strVal(list_nth(fdw_private, hdfsFdwScanPrivateSelectSql));
*/
enum hdfsFdwScanPrivateIndex
{
/* SQL statement to execute remotely (as a String node) */
hdfsFdwScanPrivateSelectSql,
/* Integer list of attribute numbers retrieved by the SELECT */
hdfsFdwScanPrivateRetrievedAttrs,
/*
* String describing join i.e. names of relations being joined and types
* of join, added when the scan is join.
*/
hdfsFdwScanPrivateRelations,
/*
* List of Var node lists for constructing the whole-row references of
* base relations involved in pushed down join.
*/
hdfsFdwPrivateWholeRowLists,
/*
* Targetlist representing the result fetched from the foreign server if
* whole-row references are involved.
*/
hdfsFdwPrivateScanTList
};
/*
* This enum describes what's kept in the fdw_private list for a ForeignPath.
* We store:
*
* 1) Boolean flag showing if the remote query has the final sort
* 2) Boolean flag showing if the remote query has the LIMIT clause
*/
enum FdwPathPrivateIndex
{
/* has-final-sort flag (as an integer Value node) */
FdwPathPrivateHasFinalSort,
/* has-limit flag (as an integer Value node) */
FdwPathPrivateHasLimit
};
/*
* Structure to hold information for constructing a whole-row reference value
* for a single base relation involved in a pushed down join.
*/
typedef struct
{
/*
* Tuple descriptor for whole-row reference. We can not use the base
* relation's tuple descriptor as it is, since it might have information
* about dropped attributes.
*/
TupleDesc tupdesc;
/*
* Positions of the required attributes in the tuple fetched from the
* foreign server.
*/
int *attr_pos;
/* Position of attribute indicating NULL-ness of whole-row reference */
int wr_null_ind_pos;
/* Values and null array for holding column values. */
Datum *values;
bool *nulls;
} hdfsWRState;
typedef struct hdfsFdwExecutionState
{
char *query;
MemoryContext batch_cxt;
bool query_executed;
int con_index;
Relation rel; /* relcache entry for the foreign table */
List *retrieved_attrs; /* list of retrieved attribute numbers */
/* For remote query execution. */
int numParams; /* number of parameters passed to query */
List *param_exprs; /* executable expressions for param values */
Oid *param_types; /* type of query parameters */
int rescan_count; /* number of times a foreign scan is restarted */
AttInMetadata *attinmeta;
/*
* Members used for constructing the ForeignScan result row when whole-row
* references are involved in a pushed down join.
*/
hdfsWRState **hdfswrstates; /* whole-row construction information for each
* base relation involved in the pushed down
* join. */
int *wr_attrs_pos; /* Array mapping the attributes in the
* ForeignScan result to those in the rows
* fetched from the foreign server. The array
* is indexed by the attribute numbers in the
* ForeignScan. */
TupleDesc wr_tupdesc; /* Tuple descriptor describing the result of
* ForeignScan node. Should be same as that in
* ForeignScanState::ss::ss_ScanTupleSlot */
/* Array for holding column values. */
Datum *wr_values;
bool *wr_nulls;
} hdfsFdwExecutionState;
extern void _PG_init(void);
extern void _PG_fini(void);
/*
* SQL functions
*/
PG_FUNCTION_INFO_V1(hdfs_fdw_handler);
PG_FUNCTION_INFO_V1(hdfs_fdw_version);
/*
* FDW callback routines
*/
static void hdfsGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel,
Oid foreigntableid);
static void hdfsGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel,
Oid foreigntableid);
static ForeignScan *hdfsGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path, List *tlist,
List *scan_clauses, Plan *outer_plan);
static void hdfsBeginForeignScan(ForeignScanState *node, int eflags);
static TupleTableSlot *hdfsIterateForeignScan(ForeignScanState *node);
static void hdfsReScanForeignScan(ForeignScanState *node);
static void hdfsEndForeignScan(ForeignScanState *node);
static void hdfsExplainForeignScan(ForeignScanState *node, ExplainState *es);
static bool hdfsAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
static void hdfsGetForeignJoinPaths(PlannerInfo *root, RelOptInfo *joinrel,
RelOptInfo *outerrel, RelOptInfo *innerrel,
JoinType jointype,
JoinPathExtraData *extra);
static bool hdfsRecheckForeignScan(ForeignScanState *node,
TupleTableSlot *slot);
static void hdfsGetForeignUpperPaths(PlannerInfo *root,
UpperRelationKind stage,
RelOptInfo *input_rel,
RelOptInfo *output_rel,
void *extra);
/*
* Helper functions
*/
static void prepare_query_params(PlanState *node,
List *fdw_exprs,
List **param_exprs,
Oid **param_types);
static void process_query_params(int index,
ExprContext *econtext,
List *param_exprs,
Oid *param_types);
static int GetConnection(hdfs_opt *opt, Oid foreigntableid);
static bool hdfs_foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel,
JoinType jointype, RelOptInfo *outerrel,
RelOptInfo *innerrel,
JoinPathExtraData *extra);
static bool hdfs_foreign_grouping_ok(PlannerInfo *root,
RelOptInfo *grouped_rel,
Node *havingQual);
static void hdfs_add_foreign_grouping_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *grouped_rel,
GroupPathExtraData *extra);
#ifdef EDB_NATIVE_LANG
#define XACT_CB_SIGNATURE XactEvent event, void *arg
#else
#define XACT_CB_SIGNATURE XactEvent event, void *arg
#endif
static List *hdfs_build_scan_list_for_baserel(Oid relid, Index varno,
Bitmapset *attrs_used,
List **retrieved_attrs);
static void hdfs_build_whole_row_constr_info(hdfsFdwExecutionState *festate,
TupleDesc tupdesc,
Bitmapset *relids,
int max_relid,
List *whole_row_lists,
List *scan_tlist,
List *fdw_scan_tlist);
static HeapTuple hdfs_get_tuple_with_whole_row(hdfsFdwExecutionState *festate,
Datum *values, bool *nulls);
static HeapTuple hdfs_form_whole_row(hdfsWRState *wr_state, Datum *values,
bool *nulls);
static void hdfs_fdw_xact_callback(XACT_CB_SIGNATURE);
static List *hdfs_get_useful_ecs_for_relation(PlannerInfo *root,
RelOptInfo *rel);
static List *hdfs_get_useful_pathkeys_for_relation(PlannerInfo *root,
RelOptInfo *rel);
#if PG_VERSION_NUM >= 170000
static void hdfs_add_paths_with_pathkeys(PlannerInfo *root,
RelOptInfo *rel,
Path *epq_path,
Cost base_startup_cost,
Cost base_total_cost,
List *restrictlist);
#else
static void hdfs_add_paths_with_pathkeys(PlannerInfo *root,
RelOptInfo *rel,
Path *epq_path,
Cost base_startup_cost,
Cost base_total_cost);
#endif
static void hdfs_add_foreign_ordered_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *ordered_rel);
static void hdfs_add_foreign_final_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *final_rel,
FinalPathExtraData *extra);
#if PG_VERSION_NUM >= 160000
static TargetEntry *hdfs_tlist_member_match_var(Var *var, List *targetlist);
static List *hdfs_varlist_append_unique_var(List *varlist, Var *var);
#endif
Datum
hdfs_fdw_version(PG_FUNCTION_ARGS)
{
PG_RETURN_INT32(CODE_VERSION);
}
void
_PG_init(void)
{
int rc = 0;
DefineCustomStringVariable("hdfs_fdw.classpath",
"Specify the path to HiveJdbcClient-X.X.jar, hadoop-common-X.X.X.jar and hive-jdbc-X.X.X-standalone.jar",
NULL,
&g_classpath,
"",
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomStringVariable("hdfs_fdw.jvmpath",
"Specify the path to libjvm.so",
NULL,
&g_jvmpath,
"",
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("hdfs_fdw.enable_join_pushdown",
"enable/disable join pushdown",
NULL,
&enable_join_pushdown,
true,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("hdfs_fdw.enable_aggregate_pushdown",
"Enable/Disable aggregate push down",
NULL,
&enable_aggregate_pushdown,
true,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
/*
* ORDER BY is inefficient in Hive so it's disabled by default in
* hdfs_fdw.
*/
DefineCustomBoolVariable("hdfs_fdw.enable_order_by_pushdown",
"Enable/Disable ORDER BY push down",
NULL,
&enable_order_by_pushdown,
false,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("hdfs_fdw.enable_limit_pushdown",
"Enable/Disable LIMIT/OFFSET push down",
NULL,
&enable_limit_pushdown,
true,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
rc = Initialize();
if (rc == -1)
{
/* TODO: The error hint is linux specific */
ereport(ERROR,
(errmsg("could not load JVM"),
errhint("Add path of libjvm.so to hdfs_fdw.jvmpath.")));
}
if (rc == -2)
ereport(ERROR,
(errmsg("class not found"),
errhint("Add path of HiveJdbcClient-X.X.jar to hdfs_fdw.classpath.")));
if (rc < 0)
ereport(ERROR,
(errmsg("initialize failed with code %d", rc)));
}
void
_PG_fini(void)
{
Destroy();
}
/*
* hdfs_fdw_xact_callback --- cleanup at main-transaction end.
*/
static void
hdfs_fdw_xact_callback(XACT_CB_SIGNATURE)
{
int nestingLevel = 0;
nestingLevel = DBCloseAllConnections();
if (nestingLevel > 0)
ereport(DEBUG1,
(errmsg("hdfs_fdw: %d connection(s) closed", nestingLevel)));
}
/*
* Foreign-data wrapper handler function, return the pointer of callback
* functions pointers
*/
Datum
hdfs_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *routine = makeNode(FdwRoutine);
/* Functions for scanning foreign tables */
routine->GetForeignRelSize = hdfsGetForeignRelSize;
routine->GetForeignPaths = hdfsGetForeignPaths;
routine->GetForeignPlan = hdfsGetForeignPlan;
routine->BeginForeignScan = hdfsBeginForeignScan;
routine->IterateForeignScan = hdfsIterateForeignScan;
routine->ReScanForeignScan = hdfsReScanForeignScan;
routine->EndForeignScan = hdfsEndForeignScan;
/* Function for EvalPlanQual rechecks */
routine->RecheckForeignScan = hdfsRecheckForeignScan;
/* Support functions for EXPLAIN */
routine->ExplainForeignScan = hdfsExplainForeignScan;
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = hdfsAnalyzeForeignTable;
/* Support functions for join push-down */
routine->GetForeignJoinPaths = hdfsGetForeignJoinPaths;
/* Support functions for upper relation push-down */
routine->GetForeignUpperPaths = hdfsGetForeignUpperPaths;
RegisterXactCallback(hdfs_fdw_xact_callback, NULL);
PG_RETURN_POINTER(routine);
}
/*
* GetConnection
* Create a connection to Hive/Spark server.
*/
static int
GetConnection(hdfs_opt *opt, Oid foreigntableid)
{
Oid userid = GetUserId();
ForeignServer *server;
ForeignTable *table;
table = GetForeignTable(foreigntableid);
server = GetForeignServer(table->serverid);
/* Connect to the server */
return hdfs_get_connection(server, opt);
}
/*
* hdfsGetForeignRelSize
* Estimate # of rows and width of the result of the scan
*
* We should consider the effect of all baserestrictinfo clauses here, but
* not any join clauses.
*/
static void
hdfsGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel,
Oid foreigntableid)
{
HDFSFdwRelationInfo *fpinfo;
ListCell *lc;
hdfs_opt *options;
RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
const char *database;
const char *relname;
const char *refname;
/*
* We use HDFSFdwRelationInfo to pass various information to subsequent
* functions.
*/
fpinfo = (HDFSFdwRelationInfo *) palloc0(sizeof(HDFSFdwRelationInfo));
baserel->fdw_private = (void *) fpinfo;
/* Base foreign tables need to be push down always. */
fpinfo->pushdown_safe = true;
fpinfo->fdw_startup_cost = DEFAULT_FDW_STARTUP_COST;
fpinfo->fdw_tuple_cost = DEFAULT_FDW_TUPLE_COST;
/*
* Identify which baserestrictinfo clauses can be sent to the remote
* server and which can't.
*/
hdfs_classify_conditions(root, baserel, baserel->baserestrictinfo,
&fpinfo->remote_conds, &fpinfo->local_conds);
/*
* Identify which attributes will need to be retrieved from the remote
* server. These include all attrs needed for joins or final output, plus
* all attrs used in the local_conds. (Note: if we end up using a
* parameterized scan, it's possible that some of the join clauses will be
* sent to the remote and thus we wouldn't really need to retrieve the
* columns used in them. Doesn't seem worth detecting that case though.)
*/
fpinfo->attrs_used = NULL;
pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid,
&fpinfo->attrs_used);
foreach(lc, fpinfo->local_conds)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
pull_varattnos((Node *) rinfo->clause, baserel->relid,
&fpinfo->attrs_used);
}
/*
* Get the actual number of rows from server if use_remote_estimate is
* specified in options, if not, assume 1000.
*/
options = hdfs_get_options(foreigntableid);
if (options->use_remote_estimate)
{
int con_index;
/* Connect to HIVE server */
con_index = GetConnection(options, foreigntableid);
baserel->rows = hdfs_rowcount(con_index, options, root,
baserel, fpinfo);
hdfs_rel_connection(con_index);
}
else
baserel->rows = 1000;
fpinfo->rows = baserel->tuples = baserel->rows;
/* Also store the options in fpinfo for further use */
fpinfo->options = options;
/* Set the flag enable_aggregate_pushdown of the base relation */
fpinfo->enable_aggregate_pushdown = options->enable_aggregate_pushdown;
/* Set the flag enable_order_by_pushdown of the base relation */
fpinfo->enable_order_by_pushdown = options->enable_order_by_pushdown;
fpinfo->client_type = options->client_type;
/*
* Set the name of relation in fpinfo, while we are constructing it here.
* It will be used to build the string describing the join relation in
* EXPLAIN output. We can't know whether VERBOSE option is specified or
* not, so always schema-qualify the foreign table name.
*/
fpinfo->relation_name = makeStringInfo();
database = options->dbname;
relname = get_rel_name(foreigntableid);
refname = rte->eref->aliasname;
appendStringInfo(fpinfo->relation_name, "%s.%s",
quote_identifier(database),
quote_identifier(relname));
if (*refname && strcmp(refname, relname) != 0)
appendStringInfo(fpinfo->relation_name, " %s",
quote_identifier(rte->eref->aliasname));
/* No outer and inner relations. */
fpinfo->make_outerrel_subquery = false;
fpinfo->make_innerrel_subquery = false;
fpinfo->lower_subquery_rels = NULL;
/* Set the relation index. */
fpinfo->relation_index = baserel->relid;
}
/*
* hdfsGetForeignPaths
* Create possible scan paths for a scan on the foreign table.
*/
static void
hdfsGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
{
HDFSFdwRelationInfo *fpinfo = (HDFSFdwRelationInfo *) baserel->fdw_private;
int total_cost;
ForeignPath *path;
total_cost = fpinfo->fdw_startup_cost +
fpinfo->fdw_tuple_cost * baserel->rows;
/*
* Create simplest ForeignScan path node and add it to baserel. This path
* corresponds to SeqScan path of regular tables (though depending on what
* baserestrict conditions we were able to send to remote, there might
* actually be an indexscan happening there). We already did all the work
* to estimate cost and size of this path.
*/
#if PG_VERSION_NUM >= 170000
path = create_foreignscan_path(root, baserel,
NULL, /* default pathtarget */
fpinfo->rows,
fpinfo->fdw_startup_cost,
total_cost,
NIL, /* no pathkeys */
baserel->lateral_relids,
NULL, /* no extra plan */
NIL, /* no fdw_restrictinfo list */
NIL); /* no fdw_private data */
#else
path = create_foreignscan_path(root, baserel,
NULL, /* default pathtarget */
fpinfo->rows,
fpinfo->fdw_startup_cost,
total_cost,
NIL, /* no pathkeys */
baserel->lateral_relids,
NULL, /* no extra plan */
NIL); /* no fdw_private data */
#endif
add_path(baserel, (Path *) path);
/* Add paths with pathkeys */
#if PG_VERSION_NUM >= 170000
hdfs_add_paths_with_pathkeys(root, baserel, NULL, fpinfo->fdw_startup_cost,
total_cost, NIL);
#else
hdfs_add_paths_with_pathkeys(root, baserel, NULL, fpinfo->fdw_startup_cost,
total_cost);
#endif
}
/*
* hdfsGetForeignPlan
* Create ForeignScan plan node which implements selected best path
*/
static ForeignScan *
hdfsGetForeignPlan(PlannerInfo *root,
RelOptInfo *foreignrel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses,
Plan *outer_plan)
{
HDFSFdwRelationInfo *fpinfo = (HDFSFdwRelationInfo *) foreignrel->fdw_private;
Index scan_relid;
List *fdw_private;
List *remote_conds = NIL;
List *remote_exprs = NIL;
List *local_exprs = NIL;
List *params_list = NIL;
List *retrieved_attrs;
StringInfoData sql;
ListCell *lc;
List *fdw_scan_tlist = NIL;
List *scan_var_list = NIL;
List *whole_row_lists = NIL;
bool has_final_sort = false;
bool has_limit = false;
/*
* Get FDW private data created by hdfsGetForeignUpperPaths(), if any.
*/
if (best_path->fdw_private)
{
has_final_sort = intVal(list_nth(best_path->fdw_private,
FdwPathPrivateHasFinalSort));
has_limit = intVal(list_nth(best_path->fdw_private,
FdwPathPrivateHasLimit));
}
if (foreignrel->reloptkind == RELOPT_BASEREL ||
foreignrel->reloptkind == RELOPT_OTHER_MEMBER_REL)
scan_relid = foreignrel->relid;
else
{
scan_relid = 0;
Assert(!scan_clauses);
remote_conds = fpinfo->remote_conds;
local_exprs = extract_actual_clauses(fpinfo->local_conds, false);
}
/*
* Separate the scan_clauses into those that can be executed remotely and
* those that can't. baserestrictinfo clauses that were previously
* determined to be safe or unsafe by hdfs_classify_conditions are shown
* in fpinfo->remote_conds and fpinfo->local_conds. Anything else in the
* scan_clauses list will be a join clause, which we have to check for
* remote-safety.
*
* This code must match "extract_actual_clauses(scan_clauses, false)"
* except for the additional decision about remote versus local execution.
* Note however that we only strip the RestrictInfo nodes from the
* local_exprs list, since appendWhereClause expects a list of
* RestrictInfos.
*/
foreach(lc, scan_clauses)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
Assert(IsA(rinfo, RestrictInfo));
/* Ignore any pseudoconstants, they're dealt with elsewhere */
if (rinfo->pseudoconstant)
continue;
if (list_member_ptr(fpinfo->remote_conds, rinfo))
{
remote_conds = lappend(remote_conds, rinfo);
remote_exprs = lappend(remote_exprs, rinfo->clause);
}
else if (list_member_ptr(fpinfo->local_conds, rinfo))
local_exprs = lappend(local_exprs, rinfo->clause);
else if (hdfs_is_foreign_expr(root, foreignrel, rinfo->clause, false))
{
remote_conds = lappend(remote_conds, rinfo);
remote_exprs = lappend(remote_exprs, rinfo->clause);
}
else
local_exprs = lappend(local_exprs, rinfo->clause);
}
if (IS_JOIN_REL(foreignrel))
{
/* Build the list of columns to be fetched from the foreign server. */
scan_var_list = pull_var_clause((Node *) foreignrel->reltarget->exprs,
PVC_RECURSE_PLACEHOLDERS);
scan_var_list = list_concat_unique(NIL, scan_var_list);
scan_var_list = list_concat_unique(scan_var_list,
pull_var_clause((Node *) local_exprs,
PVC_RECURSE_PLACEHOLDERS));
/*
* For join relations, planner needs targetlist, which represents the
* output of ForeignScan node. Prepare this before we modify
* scan_var_list to include Vars required by whole row references, if
* any. Note that base foreign scan constructs the whole-row
* reference at the time of projection. Joins are required to get
* them from the underlying base relations. For a pushed down join
* the underlying relations do not exist, hence the whole-row
* references need to be constructed separately.
*/
fdw_scan_tlist = add_to_flat_tlist(NIL, scan_var_list);
/*
* hive/spark does not allow row value constructors to be part of
* SELECT list. Hence, whole row reference in join relations need to
* be constructed by combining all the attributes of required base
* relations into a tuple after fetching the result from the foreign
* server. So adjust the targetlist to include all attributes for
* required base relations. The function also returns list of Var
* node lists required to construct the whole-row references of the
* involved relations.
*/
scan_var_list = hdfs_adjust_whole_row_ref(root, scan_var_list,
&whole_row_lists,
foreignrel->relids);
if (outer_plan)
{
/*
* Right now, we only consider grouping and aggregation beyond
* joins. Queries involving aggregates or grouping do not require
* EPQ mechanism, hence should not have an outer plan here.
*/
Assert(!IS_UPPER_REL(foreignrel));
foreach(lc, local_exprs)
{
Node *qual = lfirst(lc);
outer_plan->qual = list_delete(outer_plan->qual, qual);
/*
* For an inner join the local conditions of foreign scan plan
* can be part of the joinquals as well. (They might also be
* in the mergequals or hashquals, but we can't touch those
* without breaking the plan.)
*/
if (IsA(outer_plan, NestLoop) ||
IsA(outer_plan, MergeJoin) ||
IsA(outer_plan, HashJoin))
{
Join *join_plan = (Join *) outer_plan;
if (join_plan->jointype == JOIN_INNER)
join_plan->joinqual = list_delete(join_plan->joinqual,
qual);
}
}
}
}
else if (IS_UPPER_REL(foreignrel))
{
/*
* scan_var_list should have expressions and not TargetEntry nodes.
* However grouped_tlist created has TLEs, thus retrieve them into
* scan_var_list.
*/
scan_var_list = list_concat_unique(NIL,
get_tlist_exprs(fpinfo->grouped_tlist,
false));
/*
* The targetlist computed while assessing push-down safety represents
* the result we expect from the foreign server.
*/
fdw_scan_tlist = fpinfo->grouped_tlist;
local_exprs = extract_actual_clauses(fpinfo->local_conds, false);
}
/*
* Build the query string to be sent for execution, and identify
* expressions to be sent as parameters.
*/
initStringInfo(&sql);
hdfs_deparse_select_stmt_for_rel(&sql, root, foreignrel, scan_var_list,
remote_conds, false,
best_path->path.pathkeys,
has_final_sort, has_limit,
&retrieved_attrs,
¶ms_list);
/*
* Build the fdw_private list that will be available to the executor.
* Items in the list must match enum FdwScanPrivateIndex, above.
*/
fdw_private = list_make2(makeString(sql.data),
retrieved_attrs);
if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel))
{
fdw_private = lappend(fdw_private,
makeString(fpinfo->relation_name->data));
/*
* To construct whole row references we need:
*
* 1. The lists of Var nodes required for whole-row references of
* joining relations
*
* 2. targetlist corresponding the result expected from the foreign
* server.
*/
if (whole_row_lists)
{
fdw_private = lappend(fdw_private, whole_row_lists);
fdw_private = lappend(fdw_private,
add_to_flat_tlist(NIL, scan_var_list));
}
}
/*
* Create the ForeignScan node from target list, local filtering
* expressions, remote parameter expressions, and FDW private information.
*
* Note that the remote parameter expressions are stored in the fdw_exprs
* field of the finished plan node; we can't keep them in private state
* because then they wouldn't be subject to later planner processing.
*/
return make_foreignscan(tlist,
local_exprs,
scan_relid,
params_list,
fdw_private
,fdw_scan_tlist
,remote_exprs
,outer_plan
);
}
/*
* hdfsBeginForeignScan
* Create ForeignScan plan node which implements selected best path.
*/
static void
hdfsBeginForeignScan(ForeignScanState *node, int eflags)
{
TupleTableSlot *tupleSlot = node->ss.ss_ScanTupleSlot;
TupleDesc tupleDescriptor = tupleSlot->tts_tupleDescriptor;
ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
hdfsFdwExecutionState *festate;
RangeTblEntry *rte;
hdfs_opt *opt;
EState *estate = node->ss.ps.state;
int rtindex;
List *fdw_private = fsplan->fdw_private;
festate = (hdfsFdwExecutionState *) palloc0(sizeof(hdfsFdwExecutionState));
node->fdw_state = (void *) festate;
/*
* If whole-row references are involved in pushed down join extract the
* information required to construct those.
*/
if (list_length(fdw_private) >= hdfsFdwPrivateScanTList)
{
List *whole_row_lists = list_nth(fdw_private,
hdfsFdwPrivateWholeRowLists);
List *scan_tlist = list_nth(fdw_private,
hdfsFdwPrivateScanTList);
TupleDesc scan_tupdesc = ExecTypeFromTL(scan_tlist);
hdfs_build_whole_row_constr_info(festate, tupleDescriptor,
fsplan->fs_relids,
list_length(node->ss.ps.state->es_range_table),
whole_row_lists, scan_tlist,
fsplan->fdw_scan_tlist);
/* Change tuple descriptor to match the result from foreign server. */
tupleDescriptor = scan_tupdesc;
}
if (fsplan->scan.scanrelid > 0)
rtindex = fsplan->scan.scanrelid;
else
#if PG_VERSION_NUM >= 160000
rtindex = bms_next_member(fsplan->fs_base_relids, -1);
#else
rtindex = bms_next_member(fsplan->fs_relids, -1);
#endif
#if PG_VERSION_NUM >= 160000
rte = exec_rt_fetch(rtindex, estate);
#else
rte = rt_fetch(rtindex, estate->es_range_table);
#endif
opt = hdfs_get_options(rte->relid);
festate->con_index = GetConnection(opt, rte->relid);
festate->batch_cxt = AllocSetContextCreate(estate->es_query_cxt,
"hdfs_fdw tuple data",
ALLOCSET_DEFAULT_SIZES);
festate->query_executed = false;
festate->query = strVal(list_nth(fdw_private, hdfsFdwScanPrivateSelectSql));
festate->retrieved_attrs = (List *) list_nth(fdw_private,
hdfsFdwScanPrivateRetrievedAttrs);
festate->rescan_count = 0;
festate->attinmeta = TupleDescGetAttInMetadata(tupleDescriptor);
/*
* Prepare remote query and also prepare for processing of parameters used
* in remote query, if any.
*/
hdfs_query_prepare(festate->con_index, opt, festate->query);
festate->numParams = list_length(fsplan->fdw_exprs);
if (festate->numParams > 0)
{
prepare_query_params((PlanState *) node,
fsplan->fdw_exprs,
&festate->param_exprs,
&festate->param_types);
}
}
/*
* hdfsIterateForeignScan
* Retrieve next row from the result set and store in the tuple slot.
*/
static TupleTableSlot *
hdfsIterateForeignScan(ForeignScanState *node)
{
ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
RangeTblEntry *rte;
int rtindex;
EState *estate = node->ss.ps.state;
Datum *values;
bool *nulls;
int natts;
hdfs_opt *options;
hdfsFdwExecutionState *festate = (hdfsFdwExecutionState *) node->fdw_state;
TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
MemoryContext oldcontext;