forked from EnterpriseDB/mongo_fdw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo_fdw.c
2215 lines (1913 loc) · 63.8 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-2014, EnterpriseDB Corporation.
*
* Portions Copyright (c) 2012–2014 Citus Data, Inc.
*
* IDENTIFICATION
* mongo_fdw.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "bson.h"
#include "mongo_wrapper.h"
#include "mongo_fdw.h"
#include "mongo_query.h"
#include "access/reloptions.h"
#if PG_VERSION_NUM >= 120000
#include "access/table.h"
#endif
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "commands/vacuum.h"
#include "foreign/fdwapi.h"
#include "foreign/foreign.h"
#include "nodes/makefuncs.h"
#include "optimizer/cost.h"
#if PG_VERSION_NUM >= 120000
#include "optimizer/optimizer.h"
#endif
#include "optimizer/pathnode.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "storage/ipc.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/date.h"
#include "utils/hsearch.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/memutils.h"
#include "access/sysattr.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "commands/vacuum.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/cost.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/planmain.h"
#include "optimizer/prep.h"
#include "optimizer/restrictinfo.h"
#if PG_VERSION_NUM < 120000
#include "optimizer/var.h"
#endif
#include "parser/parsetree.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/jsonapi.h"
#include "utils/jsonb.h"
#if PG_VERSION_NUM >= 90300
#include "access/htup_details.h"
#endif
/*
* In PG 9.5.1 the number will be 90501,
* our version is 5.1.0 so number will be 50100
*/
#define CODE_VERSION 50201
/* Local functions forward declarations */
static void MongoGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel,
Oid foreignTableId);
static void MongoGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel,
Oid foreignTableId);
static ForeignScan *
MongoGetForeignPlan(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *targetlist,
List *restrictionClauses,
Plan *outer_plan);
static void MongoExplainForeignScan(ForeignScanState *scanState,
ExplainState *explainState);
static void MongoBeginForeignScan(ForeignScanState *scanState, int executorFlags);
static TupleTableSlot * MongoIterateForeignScan(ForeignScanState *scanState);
static void MongoEndForeignScan(ForeignScanState *scanState);
static void MongoReScanForeignScan(ForeignScanState *scanState);
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);
static void MongoAddForeignUpdateTargets(Query *parsetree,
RangeTblEntry *target_rte,
Relation target_relation);
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);
/* local functions */
static double ForeignTableDocumentCount(Oid foreignTableId);
static HTAB * ColumnMappingHash(Oid foreignTableId, List *columnList);
static void FillTupleSlot(const BSON *bsonDocument, const char *bsonDocumentKey,
HTAB *columnMappingHash, Datum *columnValues,
bool *columnNulls);
static bool ColumnTypesCompatible(BSON_TYPE bsonType, Oid columnTypeId);
static Datum ColumnValueArray(BSON_ITERATOR *bsonIterator, Oid valueTypeId);
static Datum ColumnValue(BSON_ITERATOR *bsonIterator, Oid columnTypeId,
int32 columnTypeMod);
static void MongoFreeScanState(MongoFdwModifyState *fmstate);
static bool MongoAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *acquireSampleRowsFunc,
BlockNumber *totalPageCount);
static int MongoAcquireSampleRows(Relation relation, int errorLevel,
HeapTuple *sampleRows, int targetRowCount,
double *totalRowCount, double *totalDeadRowCount);
static void mongo_fdw_exit(int code, Datum arg);
extern PGDLLEXPORT void _PG_init(void);
const char * EscapeJsonString(const char *string);
void BsonToJsonString(StringInfo output, BSON_ITERATOR iter, bool isArray);
/* the null action object used for pure validation */
static JsonSemAction nullSemAction =
{
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL
};
/* declarations for dynamic loading */
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(mongo_fdw_handler);
PG_FUNCTION_INFO_V1(mongo_fdw_version);
/*
* Library load-time initalization, sets on_proc_exit() callback for
* backend shutdown.
*/
void
_PG_init(void)
{
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);
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->ExecForeignInsert = MongoExecForeignInsert;
fdwRoutine->BeginForeignModify = MongoBeginForeignModify;
fdwRoutine->PlanForeignModify = MongoPlanForeignModify;
fdwRoutine->AddForeignUpdateTargets = MongoAddForeignUpdateTargets;
fdwRoutine->ExecForeignUpdate = MongoExecForeignUpdate;
fdwRoutine->ExecForeignDelete = MongoExecForeignDelete;
fdwRoutine->EndForeignModify = MongoEndForeignModify;
/* support for EXPLAIN */
fdwRoutine->ExplainForeignScan = MongoExplainForeignScan;
fdwRoutine->ExplainForeignModify = MongoExplainForeignModify;
/* support for ANALYSE */
fdwRoutine->AnalyzeForeignTable = MongoAnalyzeForeignTable;
PG_RETURN_POINTER(fdwRoutine);
}
/*
* Exit callback function.
*/
static void
mongo_fdw_exit(int code, Datum arg)
{
mongo_cleanup_connection();
}
/*
* MongoGetForeignRelSize obtains relation size estimates for mongo foreign table.
*/
static void
MongoGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreignTableId)
{
double documentCount = ForeignTableDocumentCount(foreignTableId);
if (documentCount > 0.0)
{
/*
* We estimate the number of rows returned after restriction qualifiers
* are applied. This will be more accurate if analyze is run on this
* relation.
*/
List *rowClauseList = baserel->baserestrictinfo;
double rowSelectivity = clauselist_selectivity(root, rowClauseList,
0, JOIN_INNER, NULL);
double outputRowCount = clamp_row_est(documentCount * rowSelectivity);
baserel->rows = outputRowCount;
}
else
{
ereport(DEBUG1, (errmsg("could not retrieve document count for collection"),
errhint("Falling back to default estimates in planning")));
}
}
/*
* 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)
{
double tupleFilterCost = baserel->baserestrictcost.per_tuple;
double inputRowCount = 0.0;
double documentSelectivity = 0.0;
double foreignTableSize = 0;
int32 documentWidth = 0;
BlockNumber pageCount = 0;
double totalDiskAccessCost = 0.0;
double cpuCostPerDoc = 0.0;
double cpuCostPerRow = 0.0;
double totalCpuCost = 0.0;
double connectionCost = 0.0;
double documentCount = 0.0;
List *opExpressionList = NIL;
Cost startupCost = 0.0;
Cost totalCost = 0.0;
Path *foreignPath = NULL;
documentCount = ForeignTableDocumentCount(foreignTableId);
if (documentCount > 0.0)
{
/*
* We estimate the number of rows returned after restriction qualifiers
* are applied by MongoDB.
*/
opExpressionList = ApplicableOpExpressionList(baserel);
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")));
}
/* create a foreign path node */
foreignPath = (Path *) create_foreignscan_path(root, baserel,
#if PG_VERSION_NUM >= 90600
NULL, /* default pathtarget */
#endif
baserel->rows,
startupCost,
totalCost,
NIL, /* no pathkeys */
NULL, /* no outer rel either */
#if PG_VERSION_NUM >= 90500
NULL, /* no extra plan */
#endif
NULL); /* no fdw_private data */
/* add foreign path as the only possible path */
add_path(baserel, foreignPath);
}
/*
* 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 *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *targetList,
List *restrictionClauses,
Plan *outer_plan)
{
Index scanRangeTableIndex = baserel->relid;
ForeignScan *foreignScan = NULL;
List *foreignPrivateList = NIL;
List *opExpressionList = NIL;
BSON *queryDocument = NULL;
List *columnList = NIL;
/*
* We push down applicable restriction clauses to MongoDB, but for simplicity
* we currently put all the restrictionClauses into the plan node's qual
* list for the executor to re-check. So all we have to do here is strip
* RestrictInfo nodes from the clauses and ignore pseudoconstants (which
* will be handled elsewhere).
*/
restrictionClauses = extract_actual_clauses(restrictionClauses, false);
/*
* We construct the query document to have MongoDB filter its rows. We could
* also construct a column name document here to retrieve only the needed
* columns. However, we found this optimization to degrade performance on
* the MongoDB server-side, so we instead filter out columns on our side.
*/
opExpressionList = ApplicableOpExpressionList(baserel);
queryDocument = QueryDocument(foreigntableid, opExpressionList, NULL);
/* we don't need to serialize column list as lists are copiable */
columnList = ColumnList(baserel);
/* construct foreign plan with query document and column list */
foreignPrivateList = list_make2(columnList, opExpressionList);
/* only clean up the query struct */
BsonDestroy(queryDocument);
/* create the foreign scan node */
foreignScan = make_foreignscan(targetList, restrictionClauses,
scanRangeTableIndex,
NIL, /* no expressions to evaluate */
foreignPrivateList
#if PG_VERSION_NUM >= 90500
,NIL
,NIL
,NULL
#endif
);
return foreignScan;
}
/*
* MongoExplainForeignScan produces extra output for the Explain command.
*/
static void
MongoExplainForeignScan(ForeignScanState *scanState, ExplainState *explainState)
{
MongoFdwOptions *options = NULL;
StringInfo namespaceName = NULL;
Oid foreignTableId = InvalidOid;
foreignTableId = RelationGetRelid(scanState->ss.ss_currentRelation);
options = mongo_get_options(foreignTableId);
/* construct fully qualified collection name */
namespaceName = makeStringInfo();
appendStringInfo(namespaceName, "%s.%s", options->svr_database,
options->collectionName);
mongo_free_options(options);
ExplainPropertyText("Foreign Namespace", namespaceName->data, explainState);
}
static void
MongoExplainForeignModify(ModifyTableState *mtstate,
ResultRelInfo *rinfo,
List *fdw_private,
int subplan_index,
ExplainState *es)
{
MongoFdwOptions *options = NULL;
StringInfo namespaceName = NULL;
Oid foreignTableId = InvalidOid;
foreignTableId = RelationGetRelid(rinfo->ri_RelationDesc);
options = mongo_get_options(foreignTableId);
/* construct fully qualified collection name */
namespaceName = makeStringInfo();
appendStringInfo(namespaceName, "%s.%s", options->svr_database,
options->collectionName);
mongo_free_options(options);
ExplainPropertyText("Foreign Namespace", namespaceName->data, es);
}
/*
* MongoBeginForeignScan connects to the MongoDB server, and opens a cursor that
* uses the database name, collection name, and the remote query to send to the
* server. The function also creates a hash table that maps referenced column
* names to column index and type information.
*/
static void
MongoBeginForeignScan(ForeignScanState *scanState, int executorFlags)
{
MONGO_CONN *mongoConnection = NULL;
MONGO_CURSOR *mongoCursor = NULL;
Oid foreignTableId = InvalidOid;
List *columnList = NIL;
HTAB *columnMappingHash = NULL;
ForeignScan *foreignScan = NULL;
List *foreignPrivateList = NIL;
BSON *queryDocument = NULL;
MongoFdwOptions *options = NULL;
MongoFdwModifyState *fmstate = NULL;
List *opExpressionList = NIL;
RangeTblEntry *rte;
EState *estate = scanState->ss.ps.state;
ForeignScan *fsplan = (ForeignScan *) scanState->ss.ps.plan;
Oid userid;
ForeignServer *server;
UserMapping *user;
ForeignTable *table;
/* if Explain with no Analyze, do nothing */
if (executorFlags & EXEC_FLAG_EXPLAIN_ONLY)
return;
foreignTableId = RelationGetRelid(scanState->ss.ss_currentRelation);
options = mongo_get_options(foreignTableId);
fmstate = (MongoFdwModifyState *) palloc0(sizeof(MongoFdwModifyState));
/*
* Identify which user to do the remote access as. This should match what
* ExecCheckRTEPerms() does.
*/
rte = rt_fetch(fsplan->scan.scanrelid, estate->es_range_table);
userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
/* Get info about foreign table. */
fmstate->rel = scanState->ss.ss_currentRelation;
table = GetForeignTable(RelationGetRelid(fmstate->rel));
server = GetForeignServer(table->serverid);
user = GetUserMapping(userid, server->serverid);
/*
* Get connection to the foreign server. Connection manager will
* establish new connection if necessary.
*/
mongoConnection = mongo_get_connection(server, user, options);
foreignScan = (ForeignScan *) scanState->ss.ps.plan;
foreignPrivateList = foreignScan->fdw_private;
Assert(list_length(foreignPrivateList) == 2);
columnList = list_nth(foreignPrivateList, 0);
opExpressionList = list_nth(foreignPrivateList, 1);
queryDocument = QueryDocument(foreignTableId, opExpressionList, scanState);
columnMappingHash = ColumnMappingHash(foreignTableId, columnList);
/* create cursor for collection name and set query */
mongoCursor = MongoCursorCreate(mongoConnection, options->svr_database, options->collectionName, queryDocument);
/* create and set foreign execution state */
fmstate->columnMappingHash = columnMappingHash;
fmstate->mongoConnection = mongoConnection;
fmstate->mongoCursor = mongoCursor;
fmstate->queryDocument = queryDocument;
fmstate->options = options;
scanState->fdw_state = (void *) fmstate;
}
/*
* MongoIterateForeignScan reads the next document from MongoDB, converts it to
* a PostgreSQL tuple, and stores the converted tuple into the ScanTupleSlot as
* a virtual tuple.
*/
static TupleTableSlot *
MongoIterateForeignScan(ForeignScanState *scanState)
{
MongoFdwModifyState *fmstate = (MongoFdwModifyState *) scanState->fdw_state;
TupleTableSlot *tupleSlot = scanState->ss.ss_ScanTupleSlot;
MONGO_CURSOR *mongoCursor = fmstate->mongoCursor;
HTAB *columnMappingHash = fmstate->columnMappingHash;
TupleDesc tupleDescriptor = tupleSlot->tts_tupleDescriptor;
Datum *columnValues = tupleSlot->tts_values;
bool *columnNulls = tupleSlot->tts_isnull;
int32 columnCount = tupleDescriptor->natts;
/*
* We execute the protocol to load a virtual tuple into a slot. We first
* call ExecClearTuple, then fill in values / isnull arrays, and last call
* ExecStoreVirtualTuple. If we are done fetching documents from Mongo, we
* just return an empty slot as required.
*/
ExecClearTuple(tupleSlot);
/* initialize all values for this row to null */
memset(columnValues, 0, columnCount * sizeof(Datum));
memset(columnNulls, true, columnCount * sizeof(bool));
if (MongoCursorNext(mongoCursor, NULL))
{
const BSON *bsonDocument = MongoCursorBson(mongoCursor);
const char *bsonDocumentKey = NULL; /* top level document */
FillTupleSlot(bsonDocument, bsonDocumentKey,
columnMappingHash, columnValues, columnNulls);
ExecStoreVirtualTuple(tupleSlot);
}
return tupleSlot;
}
/*
* MongoEndForeignScan finishes scanning the foreign table, closes the cursor
* and the connection to MongoDB, and reclaims scan related resources.
*/
static void
MongoEndForeignScan(ForeignScanState *scanState)
{
MongoFdwModifyState *fmstate = (MongoFdwModifyState *) scanState->fdw_state;
/* if we executed a query, reclaim mongo related resources */
if (fmstate != NULL)
{
if (fmstate->options)
{
mongo_free_options(fmstate->options);
fmstate->options = NULL;
}
MongoFreeScanState(fmstate);
}
}
/*
* MongoReScanForeignScan rescans the foreign table. Note that rescans in Mongo
* end up being notably more expensive than what the planner expects them to be,
* since MongoDB cursors don't provide reset/rewind functionality.
*/
static void
MongoReScanForeignScan(ForeignScanState *scanState)
{
MongoFdwModifyState *fmstate = (MongoFdwModifyState *) scanState->fdw_state;
MONGO_CONN *mongoConnection = fmstate->mongoConnection;
MongoFdwOptions *options = NULL;
Oid foreignTableId = InvalidOid;
/* close down the old cursor */
MongoCursorDestroy(fmstate->mongoCursor);
/* reconstruct full collection name */
foreignTableId = RelationGetRelid(scanState->ss.ss_currentRelation);
options = mongo_get_options(foreignTableId);
/* reconstruct cursor for collection name and set query */
fmstate->mongoCursor = MongoCursorCreate(mongoConnection,
fmstate->options->svr_database,
fmstate->options->collectionName,
fmstate->queryDocument);
mongo_free_options(options);
}
static List *
MongoPlanForeignModify(PlannerInfo *root,
ModifyTable *plan,
Index resultRelation,
int subplan_index)
{
CmdType operation = plan->operation;
RangeTblEntry *rte = planner_rt_fetch(resultRelation, root);
Relation rel;
List *targetAttrs = NIL;
/*
* Core code already has some lock on each rel being planned, so we can
* use NoLock here.
*/
#if PG_VERSION_NUM < 120000
rel = heap_open(rte->relid, NoLock);
#else
rel = table_open(rte->relid, NoLock);
#endif
if (operation == CMD_INSERT)
{
TupleDesc tupdesc = RelationGetDescr(rel);
int attnum;
for (attnum = 1; attnum <= tupdesc->natts; attnum++)
{
#if PG_VERSION_NUM < 110000
Form_pg_attribute attr = tupdesc->attrs[attnum - 1];
#else
Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
#endif
if (!attr->attisdropped)
targetAttrs = lappend_int(targetAttrs, attnum);
}
}
else if (operation == CMD_UPDATE)
{
#if PG_VERSION_NUM >= 90500
Bitmapset *tmpset = bms_copy(rte->updatedCols);
#else
Bitmapset *tmpset = bms_copy(rte->modifiedCols);
#endif
AttrNumber col;
while ((col = bms_first_member(tmpset)) >= 0)
{
col += FirstLowInvalidHeapAttributeNumber;
if (col <= InvalidAttrNumber) /* shouldn't happen */
elog(ERROR, "system-column update is not supported");
/*
* We also disallow updates to the first column which
* happens to be the row identifier in MongoDb (_id)
*/
if (col == 1) /* shouldn't happen */
elog(ERROR, "row identifier column update is not supported");
targetAttrs = lappend_int(targetAttrs, col);
}
/* We also want the rowid column to be available for the update */
targetAttrs = lcons_int(1, targetAttrs);
}
else
{
targetAttrs = lcons_int(1, targetAttrs);
}
/*
* RETURNING list not supported
*/
if (plan->returningLists)
elog(ERROR, "RETURNING is not supported by this FDW");
heap_close(rel, NoLock);
return list_make1(targetAttrs);
}
/*
* Begin an insert/update/delete operation on a foreign table
*/
static void
MongoBeginForeignModify(ModifyTableState *mtstate,
ResultRelInfo *resultRelInfo,
List *fdw_private,
int subplan_index,
int eflags)
{
MongoFdwModifyState *fmstate = NULL;
Relation rel = resultRelInfo->ri_RelationDesc;
AttrNumber n_params = 0;
Oid typefnoid = InvalidOid;
bool isvarlena = false;
ListCell *lc = NULL;
Oid foreignTableId = InvalidOid;
/*
* Do nothing in EXPLAIN (no ANALYZE) case. resultRelInfo->ri_FdwState
* stays NULL.
*/
if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
return;
foreignTableId = RelationGetRelid(rel);
/* Begin constructing MongoFdwModifyState. */
fmstate = (MongoFdwModifyState *) palloc0(sizeof(MongoFdwModifyState));
fmstate->rel = rel;
fmstate->options = mongo_get_options(foreignTableId);
fmstate->target_attrs = (List *) list_nth(fdw_private, 0);
n_params = list_length(fmstate->target_attrs) + 1;
fmstate->p_flinfo = (FmgrInfo *) palloc0(sizeof(FmgrInfo) * n_params);
fmstate->p_nums = 0;
/* Set up for remaining transmittable parameters */
foreach(lc, fmstate->target_attrs)
{
int attnum = lfirst_int(lc);
#if PG_VERSION_NUM < 110000
Form_pg_attribute attr = RelationGetDescr(rel)->attrs[attnum - 1];
#else
Form_pg_attribute attr = TupleDescAttr(RelationGetDescr(rel), attnum - 1);
#endif
Assert(!attr->attisdropped);
getTypeOutputInfo(attr->atttypid, &typefnoid, &isvarlena);
fmgr_info(typefnoid, &fmstate->p_flinfo[fmstate->p_nums]);
fmstate->p_nums++;
}
Assert(fmstate->p_nums <= n_params);
resultRelInfo->ri_FdwState = fmstate;
}
/*
* Insert one row into a foreign table.
*/
static TupleTableSlot *
MongoExecForeignInsert(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot)
{
MongoFdwOptions *options = NULL;
MONGO_CONN *mongoConnection = NULL;
Oid foreignTableId = InvalidOid;
BSON *b = NULL;
Oid typoid;
Datum value;
bool isnull = false;
Oid userid;
ForeignServer *server;
UserMapping *user;
ForeignTable *table;
MongoFdwModifyState *fmstate = (MongoFdwModifyState *) resultRelInfo->ri_FdwState;
foreignTableId = RelationGetRelid(resultRelInfo->ri_RelationDesc);
userid = GetUserId();
/* Get info about foreign table. */
table = GetForeignTable(RelationGetRelid(fmstate->rel));
server = GetForeignServer(table->serverid);
user = GetUserMapping(userid, server->serverid);
/*
* Get connection to the foreign server. Connection manager will
* establish new connection if necessary.
*/
options = fmstate->options;
mongoConnection = mongo_get_connection(server, user, options);
b = BsonCreate();
typoid = get_atttype(foreignTableId, 1);
/* get following parameters from slot */
if (slot != NULL && fmstate->target_attrs != NIL)
{
ListCell *lc;
foreach(lc, fmstate->target_attrs)
{
int attnum = lfirst_int(lc);
value = slot_getattr(slot, attnum, &isnull);
/* first column of MongoDB's foreign table must be _id */
#if PG_VERSION_NUM < 110000
if (strcmp(slot->tts_tupleDescriptor->attrs[0]->attname.data, "_id") != 0)
#else
if (strcmp(TupleDescAttr(slot->tts_tupleDescriptor, 0)->attname.data, "_id") != 0)
#endif
elog(ERROR, "first column of MongoDB's foreign table must be \"_id\"");
if (typoid != NAMEOID)
elog(ERROR, "type of first column of MongoDB's foreign table must be \"NAME\"");
#if PG_VERSION_NUM < 110000
if (strcmp(slot->tts_tupleDescriptor->attrs[0]->attname.data, "__doc") == 0)
#else
if (strcmp(TupleDescAttr(slot->tts_tupleDescriptor, 0)->attname.data, "__doc") == 0)
#endif
continue;
if (attnum == 1)
{
/*
* Ignore the value of first column which is row identifier in MongoDb (_id)
* and let MongoDB to insert the unique value for that column.
*/
}
else
{
#if PG_VERSION_NUM < 110000
AppenMongoValue(b, slot->tts_tupleDescriptor->attrs[attnum - 1]->attname.data, value,
isnull, slot->tts_tupleDescriptor->attrs[attnum -1]->atttypid);
#else
AppenMongoValue(b, TupleDescAttr(slot->tts_tupleDescriptor, attnum-1)->attname.data, value,
isnull, TupleDescAttr(slot->tts_tupleDescriptor, attnum-1)->atttypid);
#endif
}
}
}
BsonFinish(b);
/* Now we are ready to insert tuple / document into MongoDB */
MongoInsert(mongoConnection, options->svr_database, options->collectionName, b);
BsonDestroy(b);
return slot;
}
/*
* Add column(s) needed for update/delete on a foreign table, we are using
* first column as row identification column, so we are adding that into target
* list.
*/
static void
MongoAddForeignUpdateTargets(Query *parsetree,
RangeTblEntry *target_rte,
Relation target_relation)
{
Var *var = NULL;
const char *attrname = NULL;
TargetEntry *tle = NULL;
/*
* What we need is the rowid which is the first column
*/
#if PG_VERSION_NUM < 110000
Form_pg_attribute attr = RelationGetDescr(target_relation)->attrs[0];
#else
Form_pg_attribute attr = TupleDescAttr(RelationGetDescr(target_relation), 0);
#endif
/* Make a Var representing the desired value */
var = makeVar(parsetree->resultRelation,
1,
attr->atttypid,
attr->atttypmod,
InvalidOid,
0);
/* Wrap it in a TLE with the right name ... */
attrname = NameStr(attr->attname);
tle = makeTargetEntry((Expr *) var,
list_length(parsetree->targetList) + 1,
pstrdup(attrname),
true);
/* ... and add it to the query's targetlist */
parsetree->targetList = lappend(parsetree->targetList, tle);
}
static TupleTableSlot *
MongoExecForeignUpdate(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot)
{
MongoFdwOptions *options = NULL;
MONGO_CONN *mongoConnection = NULL;
Datum datum = 0;
bool isNull = false;
Oid foreignTableId = InvalidOid;
char *columnName = NULL;
Oid typoid = InvalidOid;
BSON *b = NULL;
BSON *op = NULL;
BSON set;
Oid userid = GetUserId();
ForeignServer *server;
UserMapping *user;
ForeignTable *table;
MongoFdwModifyState *fmstate = (MongoFdwModifyState *) resultRelInfo->ri_FdwState;
foreignTableId = RelationGetRelid(resultRelInfo->ri_RelationDesc);
/* resolve foreign table options; and connect to mongo server */
options = fmstate->options;
/* Get info about foreign table. */
table = GetForeignTable(foreignTableId);
server = GetForeignServer(table->serverid);
user = GetUserMapping(userid, server->serverid);
/*
* Get connection to the foreign server. Connection manager will
* establish new connection if necessary.
*/
mongoConnection = mongo_get_connection(server, user, options);
/* Get the id that was passed up as a resjunk column */
datum = ExecGetJunkAttribute(planSlot, 1, &isNull);
#if PG_VERSION_NUM < 110000
columnName = get_relid_attribute_name(foreignTableId, 1);
#else
columnName = get_attname(foreignTableId, 1, false);
#endif
typoid = get_atttype(foreignTableId, 1);
b = BsonCreate();
BsonAppendStartObject(b, "$set", &set);
/* get following parameters from slot */
if (slot != NULL && fmstate->target_attrs != NIL)
{
ListCell *lc;
foreach(lc, fmstate->target_attrs)
{
int attnum = lfirst_int(lc);
#if PG_VERSION_NUM < 110000
Form_pg_attribute attr = slot->tts_tupleDescriptor->attrs[attnum - 1];
#else
Form_pg_attribute attr = TupleDescAttr(slot->tts_tupleDescriptor, attnum - 1);
#endif
Datum value;
bool isnull;
if (strcmp("_id", attr->attname.data) == 0)
continue;
if (strcmp("__doc", attr->attname.data) == 0)