forked from EnterpriseDB/mongo_fdw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo_fdw.c
4796 lines (4209 loc) · 137 KB
/
mongo_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
/*-------------------------------------------------------------------------
*
* mongo_fdw.c
* Foreign-data wrapper for remote MongoDB servers
*
* Portions Copyright (c) 2012-2014, PostgreSQL Global Development Group
* Portions Copyright (c) 2004-2023, EnterpriseDB Corporation.
* Portions Copyright (c) 2012–2014 Citus Data, Inc.
*
* IDENTIFICATION
* mongo_fdw.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "mongo_wrapper.h"
#include "access/htup_details.h"
#if PG_VERSION_NUM < 120000
#include "access/sysattr.h"
#endif
#if PG_VERSION_NUM >= 120000
#include "access/table.h"
#endif
#include "catalog/heap.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_type.h"
#if PG_VERSION_NUM >= 130000
#include "common/hashfn.h"
#include "common/jsonapi.h"
#endif
#include "miscadmin.h"
#include "mongo_fdw.h"
#include "mongo_query.h"
#include "nodes/nodeFuncs.h"
#if PG_VERSION_NUM >= 140000
#include "optimizer/appendinfo.h"
#endif
#if PG_VERSION_NUM >= 120000
#include "optimizer/optimizer.h"
#endif
#include "optimizer/paths.h"
#include "optimizer/tlist.h"
#if PG_VERSION_NUM < 120000
#include "optimizer/var.h"
#endif
#include "parser/parsetree.h"
#if PG_VERSION_NUM >= 160000
#include "parser/parse_relation.h"
#endif
#include "storage/ipc.h"
#include "utils/guc.h"
#include "utils/jsonb.h"
#if PG_VERSION_NUM < 130000
#include "utils/jsonapi.h"
#else
#include "utils/jsonfuncs.h"
#endif
#include "utils/rel.h"
#include "utils/selfuncs.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
/* Declarations for dynamic loading */
PG_MODULE_MAGIC;
/*
* In PG 9.5.1 the number will be 90501,
* our version is 5.5.1 so number will be 50501
*/
#define CODE_VERSION 50501
#ifdef META_DRIVER
/*
* Macro to check unsupported sorting methods. Currently, ASC NULLS FIRST and
* DESC NULLS LAST give the same sorting result on MongoDB and Postgres. So,
* sorting methods other than these are not pushed down.
*/
#define IS_PATHKEY_PUSHABLE(pathkey) \
((pathkey->pk_strategy == BTLessStrategyNumber && pathkey->pk_nulls_first) || \
(pathkey->pk_strategy != BTLessStrategyNumber && !pathkey->pk_nulls_first))
/* Maximum path keys supported by MongoDB */
#define MAX_PATHKEYS 32
/*
* 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_MONGO_SORT_MULTIPLIER 1
/* GUC variables. */
static bool enable_join_pushdown = true;
static bool enable_order_by_pushdown = true;
static bool enable_aggregate_pushdown = true;
#endif
/*
* 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
};
extern PGDLLEXPORT void _PG_init(void);
PG_FUNCTION_INFO_V1(mongo_fdw_handler);
PG_FUNCTION_INFO_V1(mongo_fdw_version);
/* FDW callback routines */
static void mongoGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
static void mongoGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
static ForeignScan *mongoGetForeignPlan(PlannerInfo *root,
RelOptInfo *foreignrel,
Oid foreigntableid,
ForeignPath *best_path,
List *targetlist,
List *restrictionClauses,
Plan *outer_plan);
static void mongoExplainForeignScan(ForeignScanState *node, ExplainState *es);
static void mongoBeginForeignScan(ForeignScanState *node, int eflags);
static TupleTableSlot *mongoIterateForeignScan(ForeignScanState *node);
static void mongoEndForeignScan(ForeignScanState *node);
static void mongoReScanForeignScan(ForeignScanState *node);
static TupleTableSlot *mongoExecForeignUpdate(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static TupleTableSlot *mongoExecForeignDelete(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static void mongoEndForeignModify(EState *estate,
ResultRelInfo *resultRelInfo);
#if PG_VERSION_NUM >= 140000
static void mongoAddForeignUpdateTargets(PlannerInfo *root,
Index rtindex,
RangeTblEntry *target_rte,
Relation target_relation);
#else
static void mongoAddForeignUpdateTargets(Query *parsetree,
RangeTblEntry *target_rte,
Relation target_relation);
#endif
static void mongoBeginForeignModify(ModifyTableState *mtstate,
ResultRelInfo *resultRelInfo,
List *fdw_private,
int subplan_index,
int eflags);
static TupleTableSlot *mongoExecForeignInsert(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static List *mongoPlanForeignModify(PlannerInfo *root,
ModifyTable *plan,
Index resultRelation,
int subplan_index);
static void mongoExplainForeignModify(ModifyTableState *mtstate,
ResultRelInfo *rinfo,
List *fdw_private,
int subplan_index,
ExplainState *es);
static bool mongoAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
static void mongoBeginForeignInsert(ModifyTableState *mtstate,
ResultRelInfo *resultRelInfo);
static void mongoEndForeignInsert(EState *estate,
ResultRelInfo *resultRelInfo);
#ifdef META_DRIVER
static void mongoGetForeignJoinPaths(PlannerInfo *root, RelOptInfo *joinrel,
RelOptInfo *outerrel,
RelOptInfo *innerrel,
JoinType jointype,
JoinPathExtraData *extra);
static void mongoGetForeignUpperPaths(PlannerInfo *root,
UpperRelationKind stage,
RelOptInfo *input_rel,
RelOptInfo *output_rel,
void *extra);
#endif
/*
* Helper functions
*/
static double foreign_table_document_count(Oid foreignTableId);
static HTAB *column_mapping_hash(Oid foreignTableId, List *columnList,
List *colNameList, List *colIsInnerList,
uint32 relType);
static void fill_tuple_slot(const BSON *bsonDocument,
const char *bsonDocumentKey,
HTAB *columnMappingHash,
Datum *columnValues,
bool *columnNulls,
uint32 relType);
static bool column_types_compatible(BSON_TYPE bsonType, Oid columnTypeId);
static Datum column_value_array(BSON_ITERATOR *bsonIterator, Oid valueTypeId);
static Datum column_value(BSON_ITERATOR *bsonIterator,
Oid columnTypeId,
int32 columnTypeMod);
static void mongo_free_scan_state(MongoFdwModifyState *fmstate);
static int mongo_acquire_sample_rows(Relation relation,
int errorLevel,
HeapTuple *sampleRows,
int targetRowCount,
double *totalRowCount,
double *totalDeadRowCount);
static void mongo_fdw_exit(int code, Datum arg);
#ifdef META_DRIVER
static bool mongo_foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel,
JoinType jointype, RelOptInfo *outerrel,
RelOptInfo *innerrel,
JoinPathExtraData *extra);
static void mongo_prepare_qual_info(List *quals, MongoRelQualInfo *qual_info);
static bool mongo_foreign_grouping_ok(PlannerInfo *root,
RelOptInfo *grouped_rel,
Node *havingQual);
static void mongo_add_foreign_grouping_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *grouped_rel,
GroupPathExtraData *extra);
#if PG_VERSION_NUM >= 120000
static void mongo_add_foreign_final_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *final_rel,
FinalPathExtraData *extra);
#endif
#endif
#ifndef META_DRIVER
static const char *escape_json_string(const char *string);
static void bson_to_json_string(StringInfo output, BSON_ITERATOR iter,
bool isArray);
#endif
static void mongoEstimateCosts(RelOptInfo *baserel, Cost *startup_cost,
Cost *total_cost, Oid foreigntableid);
#ifdef META_DRIVER
static List *mongo_get_useful_ecs_for_relation(PlannerInfo *root,
RelOptInfo *rel);
static List *mongo_get_useful_pathkeys_for_relation(PlannerInfo *root,
RelOptInfo *rel);
static void mongo_add_paths_with_pathkeys(PlannerInfo *root,
RelOptInfo *rel,
Path *epq_path,
Cost base_startup_cost,
Cost base_total_cost);
static EquivalenceMember *mongo_find_em_for_rel_target(PlannerInfo *root,
EquivalenceClass *ec,
RelOptInfo *rel);
#if PG_VERSION_NUM >= 120000
static void mongo_add_foreign_ordered_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *ordered_rel);
#endif
#endif
/* The null action object used for pure validation */
#if PG_VERSION_NUM < 130000
static JsonSemAction nullSemAction =
{
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL
};
#else
JsonSemAction nullSemAction =
{
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL
};
#endif
/*
* Library load-time initalization, sets on_proc_exit() callback for
* backend shutdown.
*/
void
_PG_init(void)
{
#ifdef META_DRIVER
/*
* Sometimes getting a join or sorted result from MongoDB server is slower
* than performing those operations locally. To have that flexibility add
* a few GUCs to control those push-downs.
*/
DefineCustomBoolVariable("mongo_fdw.enable_join_pushdown",
"enable/disable join pushdown",
NULL,
&enable_join_pushdown,
true,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("mongo_fdw.enable_order_by_pushdown",
"Enable/Disable ORDER BY push down",
NULL,
&enable_order_by_pushdown,
true,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("mongo_fdw.enable_aggregate_pushdown",
"Enable/Disable aggregate push down",
NULL,
&enable_aggregate_pushdown,
true,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
/* Initialize MongoDB C driver */
mongoc_init();
#endif
on_proc_exit(&mongo_fdw_exit, PointerGetDatum(NULL));
}
/*
* mongo_fdw_handler
* Creates and returns a struct with pointers to foreign table callback
* functions.
*/
Datum
mongo_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *fdwRoutine = makeNode(FdwRoutine);
/* Functions for scanning foreign tables */
fdwRoutine->GetForeignRelSize = mongoGetForeignRelSize;
fdwRoutine->GetForeignPaths = mongoGetForeignPaths;
fdwRoutine->GetForeignPlan = mongoGetForeignPlan;
fdwRoutine->BeginForeignScan = mongoBeginForeignScan;
fdwRoutine->IterateForeignScan = mongoIterateForeignScan;
fdwRoutine->ReScanForeignScan = mongoReScanForeignScan;
fdwRoutine->EndForeignScan = mongoEndForeignScan;
/* Support for insert/update/delete */
fdwRoutine->AddForeignUpdateTargets = mongoAddForeignUpdateTargets;
fdwRoutine->PlanForeignModify = mongoPlanForeignModify;
fdwRoutine->BeginForeignModify = mongoBeginForeignModify;
fdwRoutine->ExecForeignInsert = mongoExecForeignInsert;
fdwRoutine->ExecForeignUpdate = mongoExecForeignUpdate;
fdwRoutine->ExecForeignDelete = mongoExecForeignDelete;
fdwRoutine->EndForeignModify = mongoEndForeignModify;
/* Support for EXPLAIN */
fdwRoutine->ExplainForeignScan = mongoExplainForeignScan;
fdwRoutine->ExplainForeignModify = mongoExplainForeignModify;
/* Support for ANALYZE */
fdwRoutine->AnalyzeForeignTable = mongoAnalyzeForeignTable;
/* Partition routing and/or COPY from */
fdwRoutine->BeginForeignInsert = mongoBeginForeignInsert;
fdwRoutine->EndForeignInsert = mongoEndForeignInsert;
#ifdef META_DRIVER
/* Support function for join push-down */
fdwRoutine->GetForeignJoinPaths = mongoGetForeignJoinPaths;
/* Support functions for upper relation push-down */
fdwRoutine->GetForeignUpperPaths = mongoGetForeignUpperPaths;
#endif
PG_RETURN_POINTER(fdwRoutine);
}
/*
* mongo_fdw_exit
* Exit callback function.
*/
static void
mongo_fdw_exit(int code, Datum arg)
{
mongo_cleanup_connection();
#ifdef META_DRIVER
/* Release all memory and other resources allocated by the driver */
mongoc_cleanup();
#endif
}
/*
* MongoGetForeignRelSize
* Obtains relation size estimates for mongo foreign table.
*/
static void
mongoGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
MongoFdwRelationInfo *fpinfo;
MongoFdwOptions *options;
ListCell *lc;
char *relname;
char *database;
char *refname;
/*
* We use MongoFdwRelationInfo to pass various information to subsequent
* functions.
*/
fpinfo = (MongoFdwRelationInfo *) palloc0(sizeof(MongoFdwRelationInfo));
baserel->fdw_private = (void *) fpinfo;
/*
* Identify which baserestrictinfo clauses can be sent to the remote
* server and which can't. Only the OpExpr clauses are sent to the remote
* server.
*/
foreach(lc, baserel->baserestrictinfo)
{
RestrictInfo *ri = (RestrictInfo *) lfirst(lc);
#ifndef META_DRIVER
if (IsA(ri->clause, OpExpr) &&
mongo_is_foreign_expr(root, baserel, ri->clause, false))
#else
if (mongo_is_foreign_expr(root, baserel, ri->clause, false))
#endif
fpinfo->remote_conds = lappend(fpinfo->remote_conds, ri);
else
fpinfo->local_conds = lappend(fpinfo->local_conds, ri);
}
/* Base foreign tables need to be pushed down always. */
fpinfo->pushdown_safe = true;
/* Fetch options */
options = mongo_get_options(foreigntableid);
/*
* Retrieve exact document count for remote collection if asked,
* otherwise, use default estimate in planning.
*/
if (options->use_remote_estimate)
{
double documentCount = foreign_table_document_count(foreigntableid);
if (documentCount > 0.0)
{
double rowSelectivity;
/*
* We estimate the number of rows returned after restriction
* qualifiers are applied. This will be more accurate if analyze
* is run on this relation.
*/
rowSelectivity = clauselist_selectivity(root,
baserel->baserestrictinfo,
0, JOIN_INNER, NULL);
baserel->rows = clamp_row_est(documentCount * rowSelectivity);
}
else
ereport(DEBUG1,
(errmsg("could not retrieve document count for collection"),
errhint("Falling back to default estimates in planning.")));
}
relname = options->collectionName;
database = options->svr_database;
fpinfo->base_relname = relname;
/*
* 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 the VERBOSE option is specified
* or not, so always schema-qualify the foreign table name.
*/
fpinfo->relation_name = makeStringInfo();
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));
/* Also store the options in fpinfo for further use */
fpinfo->options = options;
#ifdef META_DRIVER
/*
* Store aggregation enable/disable option in the fpinfo directly for
* further use. This flag can be useful when options are not accessible
* in the recursive cases.
*/
fpinfo->is_agg_scanrel_pushable = options->enable_aggregate_pushdown;
/* Set the flag is_order_by_pushable of the base relation */
fpinfo->is_order_by_pushable = options->enable_order_by_pushdown;
#endif
}
/*
* mongoGetForeignPaths
* Creates the only scan path used to execute the query.
*
* Note that MongoDB may decide to use an underlying index for this scan, but
* that decision isn't deterministic or visible to us. We therefore create a
* single table scan path.
*/
static void
mongoGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
Path *foreignPath;
MongoFdwOptions *options;
Cost startupCost;
Cost totalCost;
/* Fetch options */
options = mongo_get_options(foreigntableid);
/*
* Retrieve exact document count for remote collection if asked,
* otherwise, use default estimate in planning.
*/
if (options->use_remote_estimate)
{
double documentCount = foreign_table_document_count(foreigntableid);
if (documentCount > 0.0)
{
MongoFdwRelationInfo *fpinfo = (MongoFdwRelationInfo *) baserel->fdw_private;
double tupleFilterCost = baserel->baserestrictcost.per_tuple;
double inputRowCount;
double documentSelectivity;
double foreignTableSize;
int32 documentWidth;
BlockNumber pageCount;
double totalDiskAccessCost;
double cpuCostPerDoc;
double cpuCostPerRow;
double totalCpuCost;
double connectionCost;
List *opExpressionList;
/*
* We estimate the number of rows returned after restriction
* qualifiers are applied by MongoDB.
*/
opExpressionList = fpinfo->remote_conds;
documentSelectivity = clauselist_selectivity(root,
opExpressionList, 0,
JOIN_INNER, NULL);
inputRowCount = clamp_row_est(documentCount * documentSelectivity);
/*
* We estimate disk costs assuming a sequential scan over the
* data. This is an inaccurate assumption as Mongo scatters the
* data over disk pages, and may rely on an index to retrieve the
* data. Still, this should at least give us a relative cost.
*/
documentWidth = get_relation_data_width(foreigntableid,
baserel->attr_widths);
foreignTableSize = documentCount * documentWidth;
pageCount = (BlockNumber) rint(foreignTableSize / BLCKSZ);
totalDiskAccessCost = seq_page_cost * pageCount;
/*
* The cost of processing a document returned by Mongo (input row)
* is 5x the cost of processing a regular row.
*/
cpuCostPerDoc = cpu_tuple_cost;
cpuCostPerRow = (cpu_tuple_cost * MONGO_TUPLE_COST_MULTIPLIER) + tupleFilterCost;
totalCpuCost = (cpuCostPerDoc * documentCount) + (cpuCostPerRow * inputRowCount);
connectionCost = MONGO_CONNECTION_COST_MULTIPLIER * seq_page_cost;
startupCost = baserel->baserestrictcost.startup + connectionCost;
totalCost = startupCost + totalDiskAccessCost + totalCpuCost;
}
else
ereport(DEBUG1,
(errmsg("could not retrieve document count for collection"),
errhint("Falling back to default estimates in planning.")));
}
else
{
/* Estimate default costs */
mongoEstimateCosts(baserel, &startupCost, &totalCost, foreigntableid);
}
/* Create a foreign path node */
foreignPath = (Path *) create_foreignscan_path(root, baserel,
NULL, /* default pathtarget */
baserel->rows,
startupCost,
totalCost,
NIL, /* no pathkeys */
baserel->lateral_relids,
NULL, /* no extra plan */
NULL); /* no fdw_private data */
/* Add foreign path as the only possible path */
add_path(baserel, foreignPath);
#ifdef META_DRIVER
/* Add paths with pathkeys */
mongo_add_paths_with_pathkeys(root, baserel, NULL, startupCost, totalCost);
#endif
}
/*
* mongoGetForeignPlan
* Creates a foreign scan plan node for scanning the MongoDB collection.
*
* Note that MongoDB may decide to use an underlying index for this
* scan, but that decision isn't deterministic or visible to us.
*/
static ForeignScan *
mongoGetForeignPlan(PlannerInfo *root,
RelOptInfo *foreignrel,
Oid foreigntableid,
ForeignPath *best_path,
List *targetList,
List *restrictionClauses,
Plan *outer_plan)
{
MongoFdwRelationInfo *fpinfo = (MongoFdwRelationInfo *) foreignrel->fdw_private;
Index scan_relid = foreignrel->relid;
ForeignScan *foreignScan;
List *fdw_private;
List *columnList;
List *scan_var_list;
ListCell *lc;
List *local_exprs = NIL;
List *remote_exprs = NIL;
List *fdw_scan_tlist = NIL;
List *column_name_list = NIL;
List *is_inner_column_list = NIL;
List *quals = NIL;
MongoFdwRelType mongofdwreltype;
#ifdef META_DRIVER
MongoRelQualInfo *qual_info;
MongoFdwRelationInfo *ofpinfo;
List *pathKeyList = NIL;
List *isAscSortList = NIL;
bool has_final_sort = false;
bool has_limit = false;
int64 limit_value;
int64 offset_value;
/*
* Get FDW private data created by mongoGetForeignUpperPaths(), 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));
}
#endif
/* Set scan relation id */
if (IS_SIMPLE_REL(foreignrel))
scan_relid = foreignrel->relid;
else
{
/* Join/Upper relation - set scan_relid to 0. */
scan_relid = 0;
Assert(!restrictionClauses);
/* Extract local expressions from local conditions */
foreach(lc, fpinfo->local_conds)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
Assert(IsA(rinfo, RestrictInfo));
local_exprs = lappend(local_exprs, rinfo->clause);
}
/* Extract remote expressions from remote conditions */
foreach(lc, fpinfo->remote_conds)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
Assert(IsA(rinfo, RestrictInfo));
remote_exprs = lappend(remote_exprs, rinfo->clause);
}
}
if (IS_UPPER_REL(foreignrel))
scan_var_list = pull_var_clause((Node *) fpinfo->grouped_tlist,
PVC_RECURSE_AGGREGATES);
else
scan_var_list = pull_var_clause((Node *) foreignrel->reltarget->exprs,
PVC_RECURSE_PLACEHOLDERS);
/* System attributes are not allowed. */
foreach(lc, scan_var_list)
{
Var *var = lfirst(lc);
const FormData_pg_attribute *attr;
Assert(IsA(var, Var));
if (var->varattno >= 0)
continue;
#if PG_VERSION_NUM >= 120000
attr = SystemAttributeDefinition(var->varattno);
#else
attr = SystemAttributeDefinition(var->varattno, false);
#endif
ereport(ERROR,
(errcode(ERRCODE_FDW_COLUMN_NAME_NOT_FOUND),
errmsg("system attribute \"%s\" can't be fetched from remote relation",
attr->attname.data)));
}
/*
* Separate the restrictionClauses into those that can be executed
* remotely and those that can't. baserestrictinfo clauses that were
* previously determined to be safe or unsafe are shown in
* fpinfo->remote_conds and fpinfo->local_conds. Anything else in the
* restrictionClauses list will be a join clause, which we have to check
* for remote-safety. Only the OpExpr clauses are sent to the remote
* server.
*/
foreach(lc, restrictionClauses)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
Assert(IsA(rinfo, RestrictInfo));
/* Ignore pseudoconstants, they are dealt with elsewhere */
if (rinfo->pseudoconstant)
continue;
if (list_member_ptr(fpinfo->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 (IsA(rinfo->clause, OpExpr) &&
mongo_is_foreign_expr(root, foreignrel, rinfo->clause, false))
remote_exprs = lappend(remote_exprs, rinfo->clause);
else
local_exprs = lappend(local_exprs, rinfo->clause);
}
/* Add local expression Var nodes to scan_var_list. */
scan_var_list = list_concat_unique(NIL, scan_var_list);
if (IS_UPPER_REL(foreignrel))
scan_var_list = list_concat_unique(scan_var_list,
pull_var_clause((Node *) local_exprs,
PVC_RECURSE_AGGREGATES));
else
scan_var_list = list_concat_unique(scan_var_list,
pull_var_clause((Node *) local_exprs,
PVC_RECURSE_PLACEHOLDERS));
if (IS_JOIN_REL(foreignrel))
{
/*
* For join relations, the planner needs a targetlist, which
* represents the output of the ForeignScan node.
*/
fdw_scan_tlist = add_to_flat_tlist(NIL, scan_var_list);
/*
* Ensure that the outer plan produces a tuple whose descriptor
* matches our scan tuple slot. Also, remove the local conditions
* from the outer plan's quals, lest they be evaluated twice, once by
* the local plan and once by the scan.
*/
if (outer_plan)
{
/*
* First, update the plan's qual list if possible. In some cases,
* the quals might be enforced below the topmost plan level, in
* which case we'll fail to remove them; it's not worth working
* harder than this.
*/
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 the 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);
}
}
/*
* Now fix the subplan's tlist --- this might result in inserting
* a Result node atop the plan tree.
*/
outer_plan = change_plan_targetlist(outer_plan, fdw_scan_tlist,
best_path->path.parallel_safe);
}
}
else if (IS_UPPER_REL(foreignrel))
{
/*
* scan_var_list should have expressions and not TargetEntry nodes.
* However, grouped_tlist created has TLEs, and 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);
}
/* Form column list required for query execution from scan_var_list. */
columnList = mongo_get_column_list(root, foreignrel, scan_var_list,
&column_name_list,
&is_inner_column_list);
/*
* Identify the relation type. We can have a simple base rel, join rel,
* upper rel, and upper rel with join rel inside. Find out that.
*/
if (IS_UPPER_REL(foreignrel) && IS_JOIN_REL(fpinfo->outerrel))
mongofdwreltype = UPPER_JOIN_REL;
else if (IS_UPPER_REL(foreignrel))
mongofdwreltype = UPPER_REL;
else if (IS_JOIN_REL(foreignrel))
mongofdwreltype = JOIN_REL;
else
mongofdwreltype = BASE_REL;
#ifdef META_DRIVER
/*
* We use MongoRelQualInfo to pass various information related to joining
* quals and grouping target to fdw_private which is used to form
* equivalent MongoDB query during the execution phase.
*/
qual_info = (MongoRelQualInfo *) palloc(sizeof(MongoRelQualInfo));
qual_info->root = root;
qual_info->foreignRel = foreignrel;
qual_info->exprColHash = NULL;
qual_info->colNameList = NIL;
qual_info->colNumList = NIL;
qual_info->rtiList = NIL;
qual_info->isOuterList = NIL;
qual_info->is_having = false;
qual_info->is_agg_column = false;
qual_info->aggTypeList = NIL;
qual_info->aggColList = NIL;
qual_info->isHavingList = NIL;
/*
* Prepare separate lists of information. This information would be
* useful at the time of execution to prepare the MongoDB query.
*/
if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel))
{
ofpinfo = (MongoFdwRelationInfo *) fpinfo->outerrel->fdw_private;
/*
* Save foreign relation and relid's of an outer relation involved in
* the join depending on the relation type.
*/
if (mongofdwreltype == UPPER_JOIN_REL)
{
/* For aggregation over join relation */
qual_info->foreignRel = fpinfo->outerrel;
qual_info->outerRelids = ofpinfo->outerrel->relids;
}
else if (mongofdwreltype == UPPER_REL)
{
/* For aggregation relation */
qual_info->foreignRel = fpinfo->outerrel;
qual_info->outerRelids = fpinfo->outerrel->relids;
}
else
{
Assert(mongofdwreltype == JOIN_REL);
qual_info->foreignRel = foreignrel;
qual_info->outerRelids = fpinfo->outerrel->relids;
}
/*
* Extract required data of columns involved in join clauses and
* append it into the various lists required to pass it to the
* executor.
*
* Check and extract data for outer relation and its join clauses in
* case of aggregation on top of the join operation.
*/
if (IS_JOIN_REL(foreignrel) && fpinfo->joinclauses)
mongo_prepare_qual_info(fpinfo->joinclauses, qual_info);
else if (IS_JOIN_REL(fpinfo->outerrel) && ofpinfo->joinclauses)
mongo_prepare_qual_info(ofpinfo->joinclauses, qual_info);
/*
* Extract required data of columns involved in the WHERE clause and
* append it into the various lists required to pass it to the
* executor.
*/
if (IS_JOIN_REL(foreignrel) && fpinfo->remote_conds)
mongo_prepare_qual_info(fpinfo->remote_conds, qual_info);
/* Gather required information of an upper relation */
if (IS_UPPER_REL(foreignrel))
{
/* Extract remote expressions from the remote conditions */
foreach(lc, ofpinfo->remote_conds)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
Assert(IsA(rinfo, RestrictInfo));
quals = lappend(quals, rinfo->clause);
}
/* Extract WHERE clause column information */
mongo_prepare_qual_info(quals, qual_info);
/*
* Extract grouping target information i.e grouping operation and
* grouping clause.
*/
mongo_prepare_qual_info(scan_var_list, qual_info);
/* Extract HAVING clause information */
if (fpinfo->remote_conds)
{
qual_info->is_having = true;
mongo_prepare_qual_info(fpinfo->remote_conds, qual_info);
}
}
else
quals = remote_exprs;
}
else
{
quals = remote_exprs;
/* For baserel */
qual_info->foreignRel = foreignrel;
qual_info->outerRelids = NULL;
/*
* Extract required data of columns involved in WHERE clause of the
* simple relation.
*/
mongo_prepare_qual_info(quals, qual_info);
}
#else
quals = remote_exprs;
#endif
/*
* Check the ORDER BY clause, and if we found any useful pathkeys, then
* store the required information.
*/
#ifdef META_DRIVER
foreach(lc, best_path->path.pathkeys)
{