-
Notifications
You must be signed in to change notification settings - Fork 105
/
mongo_fdw.c
1464 lines (1247 loc) · 43.6 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
*
* Function definitions for MongoDB foreign data wrapper. These functions access
* data stored in MongoDB through the official C driver.
*
* Copyright (c) 2012-2014 Citus Data, Inc.
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "mongo_fdw.h"
#include "access/reloptions.h"
#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"
#include "optimizer/pathnode.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.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"
#if PG_VERSION_NUM >= 90300
#include "access/htup_details.h"
#endif
/* Local functions forward declarations */
static StringInfo OptionNamesString(Oid currentContextId);
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 *bestPath,
List *targetList, List *restrictionClauses);
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 Const * SerializeDocument(bson *document);
static bson * DeserializeDocument(Const *constant);
static double ForeignTableDocumentCount(Oid foreignTableId);
static MongoFdwOptions * MongoGetOptions(Oid foreignTableId);
static char * MongoGetOptionValue(Oid foreignTableId, const char *optionName);
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(MongoFdwExecState *executionState);
static bool MongoAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *acquireSampleRowsFunc,
BlockNumber *totalPageCount);
static int MongoAcquireSampleRows(Relation relation, int errorLevel,
HeapTuple *sampleRows, int targetRowCount,
double *totalRowCount, double *totalDeadRowCount);
/* declarations for dynamic loading */
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(mongo_fdw_handler);
PG_FUNCTION_INFO_V1(mongo_fdw_validator);
/*
* 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->ExplainForeignScan = MongoExplainForeignScan;
fdwRoutine->BeginForeignScan = MongoBeginForeignScan;
fdwRoutine->IterateForeignScan = MongoIterateForeignScan;
fdwRoutine->ReScanForeignScan = MongoReScanForeignScan;
fdwRoutine->EndForeignScan = MongoEndForeignScan;
fdwRoutine->AnalyzeForeignTable = MongoAnalyzeForeignTable;
PG_RETURN_POINTER(fdwRoutine);
}
/*
* mongo_fdw_validator validates options given to one of the following commands:
* foreign data wrapper, server, user mapping, or foreign table. This function
* errors out if the given option name or its value is considered invalid.
*/
Datum
mongo_fdw_validator(PG_FUNCTION_ARGS)
{
Datum optionArray = PG_GETARG_DATUM(0);
Oid optionContextId = PG_GETARG_OID(1);
List *optionList = untransformRelOptions(optionArray);
ListCell *optionCell = NULL;
foreach(optionCell, optionList)
{
DefElem *optionDef = (DefElem *) lfirst(optionCell);
char *optionName = optionDef->defname;
bool optionValid = false;
int32 optionIndex = 0;
for (optionIndex = 0; optionIndex < ValidOptionCount; optionIndex++)
{
const MongoValidOption *validOption = &(ValidOptionArray[optionIndex]);
if ((optionContextId == validOption->optionContextId) &&
(strncmp(optionName, validOption->optionName, NAMEDATALEN) == 0))
{
optionValid = true;
break;
}
}
/* if invalid option, display an informative error message */
if (!optionValid)
{
StringInfo optionNamesString = OptionNamesString(optionContextId);
ereport(ERROR, (errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
errmsg("invalid option \"%s\"", optionName),
errhint("Valid options in this context are: %s",
optionNamesString->data)));
}
/* if port option is given, error out if its value isn't an integer */
if (strncmp(optionName, OPTION_NAME_PORT, NAMEDATALEN) == 0)
{
char *optionValue = defGetString(optionDef);
int32 portNumber = pg_atoi(optionValue, sizeof(int32), 0);
(void) portNumber;
}
}
PG_RETURN_VOID();
}
/*
* OptionNamesString finds all options that are valid for the current context,
* and concatenates these option names in a comma separated string.
*/
static StringInfo
OptionNamesString(Oid currentContextId)
{
StringInfo optionNamesString = makeStringInfo();
bool firstOptionPrinted = false;
int32 optionIndex = 0;
for (optionIndex = 0; optionIndex < ValidOptionCount; optionIndex++)
{
const MongoValidOption *validOption = &(ValidOptionArray[optionIndex]);
/* if option belongs to current context, append option name */
if (currentContextId == validOption->optionContextId)
{
if (firstOptionPrinted)
{
appendStringInfoString(optionNamesString, ", ");
}
appendStringInfoString(optionNamesString, validOption->optionName);
firstOptionPrinted = true;
}
}
return optionNamesString;
}
/*
* 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, baserel->rows,
startupCost, totalCost,
NIL, /* no pathkeys */
NULL, /* no outer rel either */
NIL); /* 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 *bestPath, List *targetList, List *restrictionClauses)
{
Index scanRangeTableIndex = baserel->relid;
ForeignScan *foreignScan = NULL;
List *foreignPrivateList = NIL;
List *opExpressionList = NIL;
bson *queryDocument = NULL;
Const *queryBuffer = 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);
queryBuffer = SerializeDocument(queryDocument);
/* only clean up the query struct, but not its data */
bson_dispose(queryDocument);
/* 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(queryBuffer, columnList);
/* create the foreign scan node */
foreignScan = make_foreignscan(targetList, restrictionClauses,
scanRangeTableIndex,
NIL, /* no expressions to evaluate */
foreignPrivateList);
return foreignScan;
}
/*
* MongoExplainForeignScan produces extra output for the Explain command.
*/
static void
MongoExplainForeignScan(ForeignScanState *scanState, ExplainState *explainState)
{
MongoFdwOptions *mongoFdwOptions = NULL;
StringInfo namespaceName = NULL;
Oid foreignTableId = InvalidOid;
foreignTableId = RelationGetRelid(scanState->ss.ss_currentRelation);
mongoFdwOptions = MongoGetOptions(foreignTableId);
/* construct fully qualified collection name */
namespaceName = makeStringInfo();
appendStringInfo(namespaceName, "%s.%s", mongoFdwOptions->databaseName,
mongoFdwOptions->collectionName);
ExplainPropertyText("Foreign Namespace", namespaceName->data, explainState);
}
/*
* 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 *mongoConnection = NULL;
mongo_cursor *mongoCursor = NULL;
int32 connectStatus = MONGO_ERROR;
Oid foreignTableId = InvalidOid;
List *columnList = NIL;
HTAB *columnMappingHash = NULL;
char *addressName = NULL;
int32 portNumber = 0;
int32 errorCode = 0;
StringInfo namespaceName = NULL;
ForeignScan *foreignScan = NULL;
List *foreignPrivateList = NIL;
Const *queryBuffer = NULL;
bson *queryDocument = NULL;
MongoFdwOptions *mongoFdwOptions = NULL;
MongoFdwExecState *executionState = NULL;
/* if Explain with no Analyze, do nothing */
if (executorFlags & EXEC_FLAG_EXPLAIN_ONLY)
{
return;
}
foreignTableId = RelationGetRelid(scanState->ss.ss_currentRelation);
mongoFdwOptions = MongoGetOptions(foreignTableId);
/* resolve hostname and port number; and connect to mongo server */
addressName = mongoFdwOptions->addressName;
portNumber = mongoFdwOptions->portNumber;
mongoConnection = mongo_create();
mongo_init(mongoConnection);
connectStatus = mongo_connect(mongoConnection, addressName, portNumber);
if (connectStatus != MONGO_OK)
{
errorCode = (int32) mongoConnection->err;
mongo_destroy(mongoConnection);
mongo_dispose(mongoConnection);
ereport(ERROR, (errmsg("could not connect to %s:%d", addressName, portNumber),
errhint("Mongo driver connection error: %d", errorCode)));
}
/* deserialize query document; and create column info hash */
foreignScan = (ForeignScan *) scanState->ss.ps.plan;
foreignPrivateList = foreignScan->fdw_private;
Assert(list_length(foreignPrivateList) == 2);
queryBuffer = (Const *) linitial(foreignPrivateList);
queryDocument = DeserializeDocument(queryBuffer);
columnList = (List *) lsecond(foreignPrivateList);
columnMappingHash = ColumnMappingHash(foreignTableId, columnList);
namespaceName = makeStringInfo();
appendStringInfo(namespaceName, "%s.%s", mongoFdwOptions->databaseName,
mongoFdwOptions->collectionName);
/* create cursor for collection name and set query */
mongoCursor = mongo_cursor_create();
mongo_cursor_init(mongoCursor, mongoConnection, namespaceName->data);
mongo_cursor_set_query(mongoCursor, queryDocument);
/* create and set foreign execution state */
executionState = (MongoFdwExecState *) palloc0(sizeof(MongoFdwExecState));
executionState->columnMappingHash = columnMappingHash;
executionState->mongoConnection = mongoConnection;
executionState->mongoCursor = mongoCursor;
executionState->queryDocument = queryDocument;
scanState->fdw_state = (void *) executionState;
}
/*
* 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)
{
MongoFdwExecState *executionState = (MongoFdwExecState *) scanState->fdw_state;
TupleTableSlot *tupleSlot = scanState->ss.ss_ScanTupleSlot;
mongo_cursor *mongoCursor = executionState->mongoCursor;
HTAB *columnMappingHash = executionState->columnMappingHash;
int32 cursorStatus = MONGO_ERROR;
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));
cursorStatus = mongo_cursor_next(mongoCursor);
if (cursorStatus == MONGO_OK)
{
const bson *bsonDocument = mongo_cursor_bson(mongoCursor);
const char *bsonDocumentKey = NULL; /* top level document */
FillTupleSlot(bsonDocument, bsonDocumentKey,
columnMappingHash, columnValues, columnNulls);
ExecStoreVirtualTuple(tupleSlot);
}
else
{
/*
* The following is a courtesy check. In practice when Mongo shuts down,
* mongo_cursor_next() could possibly crash. This function first frees
* cursor->reply, and then references reply in mongo_cursor_destroy().
*/
mongo_cursor_error_t errorCode = mongoCursor->err;
if (errorCode != MONGO_CURSOR_EXHAUSTED)
{
MongoFreeScanState(executionState);
ereport(ERROR, (errmsg("could not iterate over mongo collection"),
errhint("Mongo driver cursor error code: %d", errorCode)));
}
}
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)
{
MongoFdwExecState *executionState = (MongoFdwExecState *) scanState->fdw_state;
/* if we executed a query, reclaim mongo related resources */
if (executionState != NULL)
{
MongoFreeScanState(executionState);
}
}
/*
* 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)
{
MongoFdwExecState *executionState = (MongoFdwExecState *) scanState->fdw_state;
mongo *mongoConnection = executionState->mongoConnection;
MongoFdwOptions *mongoFdwOptions = NULL;
mongo_cursor *mongoCursor = NULL;
StringInfo namespaceName = NULL;
Oid foreignTableId = InvalidOid;
/* close down the old cursor */
mongo_cursor_destroy(executionState->mongoCursor);
mongo_cursor_dispose(executionState->mongoCursor);
/* reconstruct full collection name */
foreignTableId = RelationGetRelid(scanState->ss.ss_currentRelation);
mongoFdwOptions = MongoGetOptions(foreignTableId);
namespaceName = makeStringInfo();
appendStringInfo(namespaceName, "%s.%s", mongoFdwOptions->databaseName,
mongoFdwOptions->collectionName);
/* reconstruct cursor for collection name and set query */
mongoCursor = mongo_cursor_create();
mongo_cursor_init(mongoCursor, mongoConnection, namespaceName->data);
mongo_cursor_set_query(mongoCursor, executionState->queryDocument);
executionState->mongoCursor = mongoCursor;
}
/*
* SerializeDocument serializes the document's data to a constant, as advised in
* foreign/fdwapi.h. Note that this function shallow-copies the document's data;
* and the caller should therefore not free it.
*/
static Const *
SerializeDocument(bson *document)
{
Const *serializedDocument = NULL;
Datum documentDatum = 0;
/*
* We access document data and wrap a datum around it. Note that even when
* we have an empty document, the document size can't be zero according to
* bson apis.
*/
const char *documentData = bson_data(document);
int32 documentSize = bson_buffer_size(document);
Assert(documentSize != 0);
documentDatum = CStringGetDatum(documentData);
serializedDocument = makeConst(CSTRINGOID, -1, InvalidOid, documentSize,
documentDatum, false, false);
return serializedDocument;
}
/*
* DeserializeDocument deserializes the constant to a bson document. For this,
* the function creates a document, and explicitly sets the document's data.
*/
static bson *
DeserializeDocument(Const *constant)
{
bson *document = NULL;
Datum documentDatum = constant->constvalue;
char *documentData = DatumGetCString(documentDatum);
Assert(constant->constlen > 0);
Assert(constant->constisnull == false);
document = bson_create();
bson_init_size(document, 0);
bson_init_finished_data(document, documentData);
return document;
}
/*
* ForeignTableDocumentCount connects to the MongoDB server, and queries it for
* the number of documents in the foreign collection. On success, the function
* returns the document count. On failure, the function returns -1.0.
*/
static double
ForeignTableDocumentCount(Oid foreignTableId)
{
MongoFdwOptions *options = NULL;
mongo *mongoConnection = NULL;
const bson *emptyQuery = NULL;
int32 status = MONGO_ERROR;
double documentCount = 0.0;
/* resolve foreign table options; and connect to mongo server */
options = MongoGetOptions(foreignTableId);
mongoConnection = mongo_create();
mongo_init(mongoConnection);
status = mongo_connect(mongoConnection, options->addressName, options->portNumber);
if (status == MONGO_OK)
{
documentCount = mongo_count(mongoConnection, options->databaseName,
options->collectionName, emptyQuery);
}
else
{
documentCount = -1.0;
}
mongo_destroy(mongoConnection);
mongo_dispose(mongoConnection);
return documentCount;
}
/*
* MongoGetOptions returns the option values to be used when connecting to and
* querying MongoDB. To resolve these values, the function checks the foreign
* table's options, and if not present, falls back to default values.
*/
static MongoFdwOptions *
MongoGetOptions(Oid foreignTableId)
{
MongoFdwOptions *mongoFdwOptions = NULL;
char *addressName = NULL;
char *portName = NULL;
int32 portNumber = 0;
char *databaseName = NULL;
char *collectionName = NULL;
addressName = MongoGetOptionValue(foreignTableId, OPTION_NAME_ADDRESS);
if (addressName == NULL)
{
addressName = pstrdup(DEFAULT_IP_ADDRESS);
}
portName = MongoGetOptionValue(foreignTableId, OPTION_NAME_PORT);
if (portName == NULL)
{
portNumber = DEFAULT_PORT_NUMBER;
}
else
{
portNumber = pg_atoi(portName, sizeof(int32), 0);
}
databaseName = MongoGetOptionValue(foreignTableId, OPTION_NAME_DATABASE);
if (databaseName == NULL)
{
databaseName = pstrdup(DEFAULT_DATABASE_NAME);
}
collectionName = MongoGetOptionValue(foreignTableId, OPTION_NAME_COLLECTION);
if (collectionName == NULL)
{
collectionName = get_rel_name(foreignTableId);
}
mongoFdwOptions = (MongoFdwOptions *) palloc0(sizeof(MongoFdwOptions));
mongoFdwOptions->addressName = addressName;
mongoFdwOptions->portNumber = portNumber;
mongoFdwOptions->databaseName = databaseName;
mongoFdwOptions->collectionName = collectionName;
return mongoFdwOptions;
}
/*
* MongoGetOptionValue walks over foreign table and foreign server options, and
* looks for the option with the given name. If found, the function returns the
* option's value.
*/
static char *
MongoGetOptionValue(Oid foreignTableId, const char *optionName)
{
ForeignTable *foreignTable = NULL;
ForeignServer *foreignServer = NULL;
List *optionList = NIL;
ListCell *optionCell = NULL;
char *optionValue = NULL;
foreignTable = GetForeignTable(foreignTableId);
foreignServer = GetForeignServer(foreignTable->serverid);
optionList = list_concat(optionList, foreignTable->options);
optionList = list_concat(optionList, foreignServer->options);
foreach(optionCell, optionList)
{
DefElem *optionDef = (DefElem *) lfirst(optionCell);
char *optionDefName = optionDef->defname;
if (strncmp(optionDefName, optionName, NAMEDATALEN) == 0)
{
optionValue = defGetString(optionDef);
break;
}
}
return optionValue;
}
/*
* ColumnMappingHash creates a hash table that maps column names to column index
* and types. This table helps us quickly translate BSON document key/values to
* the corresponding PostgreSQL columns.
*/
static HTAB *
ColumnMappingHash(Oid foreignTableId, List *columnList)
{
ListCell *columnCell = NULL;
const long hashTableSize = 2048;
HTAB *columnMappingHash = NULL;
/* create hash table */
HASHCTL hashInfo;
memset(&hashInfo, 0, sizeof(hashInfo));
hashInfo.keysize = NAMEDATALEN;
hashInfo.entrysize = sizeof(ColumnMapping);
hashInfo.hash = string_hash;
hashInfo.hcxt = CurrentMemoryContext;
columnMappingHash = hash_create("Column Mapping Hash", hashTableSize, &hashInfo,
(HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT));
Assert(columnMappingHash != NULL);
foreach(columnCell, columnList)
{
Var *column = (Var *) lfirst(columnCell);
AttrNumber columnId = column->varattno;
ColumnMapping *columnMapping = NULL;
char *columnName = NULL;
bool handleFound = false;
void *hashKey = NULL;
columnName = get_relid_attribute_name(foreignTableId, columnId);
hashKey = (void *) columnName;
columnMapping = (ColumnMapping *) hash_search(columnMappingHash, hashKey,
HASH_ENTER, &handleFound);
Assert(columnMapping != NULL);
columnMapping->columnIndex = columnId - 1;
columnMapping->columnTypeId = column->vartype;
columnMapping->columnTypeMod = column->vartypmod;
columnMapping->columnArrayTypeId = get_element_type(column->vartype);
}
return columnMappingHash;
}
/*
* FillTupleSlot walks over all key/value pairs in the given document. For each
* pair, the function checks if the key appears in the column mapping hash, and
* if the value type is compatible with the one specified for the column. If so,
* the function converts the value and fills the corresponding tuple position.
* The bsonDocumentKey parameter is used for recursion, and should always be
* passed as NULL.
*/
static void
FillTupleSlot(const bson *bsonDocument, const char *bsonDocumentKey,
HTAB *columnMappingHash, Datum *columnValues, bool *columnNulls)
{
bson_iterator bsonIterator = { NULL, 0 };
bson_iterator_init(&bsonIterator, bsonDocument);
while (bson_iterator_next(&bsonIterator))
{
const char *bsonKey = bson_iterator_key(&bsonIterator);
bson_type bsonType = bson_iterator_type(&bsonIterator);
ColumnMapping *columnMapping = NULL;
Oid columnTypeId = InvalidOid;
Oid columnArrayTypeId = InvalidOid;
bool compatibleTypes = false;
bool handleFound = false;
const char *bsonFullKey = NULL;
void *hashKey = NULL;
if (bsonDocumentKey != NULL)
{
/*
* For fields in nested BSON objects, we use fully qualified field
* name to check the column mapping.
*/
StringInfo bsonFullKeyString = makeStringInfo();
appendStringInfo(bsonFullKeyString, "%s.%s", bsonDocumentKey, bsonKey);
bsonFullKey = bsonFullKeyString->data;
}
else
{
bsonFullKey = bsonKey;
}
/* recurse into nested objects */
if (bsonType == BSON_OBJECT)
{
bson subObject;
bson_iterator_subobject(&bsonIterator, &subObject);
FillTupleSlot(&subObject, bsonFullKey,
columnMappingHash, columnValues, columnNulls);
continue;
}
/* look up the corresponding column for this bson key */
hashKey = (void *) bsonFullKey;
columnMapping = (ColumnMapping *) hash_search(columnMappingHash, hashKey,
HASH_FIND, &handleFound);
/* if no corresponding column or null bson value, continue */
if (columnMapping == NULL || bsonType == BSON_NULL)
{
continue;
}
/* check if columns have compatible types */
columnTypeId = columnMapping->columnTypeId;
columnArrayTypeId = columnMapping->columnArrayTypeId;
if (OidIsValid(columnArrayTypeId) && bsonType == BSON_ARRAY)
{
compatibleTypes = true;
}
else
{
compatibleTypes = ColumnTypesCompatible(bsonType, columnTypeId);
}
/* if types are incompatible, leave this column null */
if (!compatibleTypes)
{
continue;
}
/* fill in corresponding column value and null flag */
if (OidIsValid(columnArrayTypeId))
{
int32 columnIndex = columnMapping->columnIndex;
columnValues[columnIndex] = ColumnValueArray(&bsonIterator,
columnArrayTypeId);
columnNulls[columnIndex] = false;
}
else
{
int32 columnIndex = columnMapping->columnIndex;
Oid columnTypeMod = columnMapping->columnTypeMod;
columnValues[columnIndex] = ColumnValue(&bsonIterator,
columnTypeId, columnTypeMod);
columnNulls[columnIndex] = false;
}
}
}
/*
* ColumnTypesCompatible checks if the given BSON type can be converted to the
* given PostgreSQL type. In this check, the function also uses its knowledge of
* internal conversions applied by BSON APIs.
*/
static bool
ColumnTypesCompatible(bson_type bsonType, Oid columnTypeId)
{
bool compatibleTypes = false;
/* we consider the PostgreSQL column type as authoritative */
switch(columnTypeId)
{
case INT2OID: case INT4OID:
case INT8OID: case FLOAT4OID:
case FLOAT8OID: case NUMERICOID:
{
if (bsonType == BSON_INT || bsonType == BSON_LONG ||
bsonType == BSON_DOUBLE)
{
compatibleTypes = true;
}
break;
}
case BOOLOID:
{
if (bsonType == BSON_INT || bsonType == BSON_LONG ||
bsonType == BSON_DOUBLE || bsonType == BSON_BOOL)
{
compatibleTypes = true;
}
break;
}
case BPCHAROID:
case VARCHAROID:
case TEXTOID:
{
if (bsonType == BSON_STRING)
{
compatibleTypes = true;
}
break;
}
case NAMEOID:
{
/*
* We currently overload the NAMEOID type to represent the BSON
* object identifier. We can safely overload this 64-byte data type
* since it's reserved for internal use in PostgreSQL.
*/
if (bsonType == BSON_OID)
{
compatibleTypes = true;
}
break;
}
case DATEOID:
case TIMESTAMPOID:
case TIMESTAMPTZOID:
{
if (bsonType == BSON_DATE)
{
compatibleTypes = true;
}
break;
}
default:
{
/*
* We currently error out on other data types. Some types such as
* byte arrays are easy to add, but they need testing. Other types
* such as money or inet, do not have equivalents in MongoDB.
*/
ereport(ERROR, (errcode(ERRCODE_FDW_INVALID_DATA_TYPE),
errmsg("cannot convert bson type to column type"),
errhint("Column type: %u", (uint32) columnTypeId)));
break;
}
}
return compatibleTypes;
}
/*