forked from citusdata/mongo_fdw
-
Notifications
You must be signed in to change notification settings - Fork 70
/
mongo_query.c
1854 lines (1638 loc) · 49.9 KB
/
mongo_query.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_query.c
* FDW query handling for mongo_fdw
*
* Portions Copyright (c) 2012-2014, PostgreSQL Global Development Group
* Portions Copyright (c) 2004-2024, EnterpriseDB Corporation.
* Portions Copyright (c) 2012–2014 Citus Data, Inc.
*
* IDENTIFICATION
* mongo_query.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "mongo_wrapper.h"
#include <bson.h>
#include <json.h>
#include "access/htup_details.h"
#include "access/table.h"
#include "catalog/heap.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_operator.h"
#if PG_VERSION_NUM >= 130000
#include "common/hashfn.h"
#endif
#include "mongoc.h"
#include "mongo_query.h"
#include "optimizer/optimizer.h"
#include "parser/parsetree.h"
#include "utils/rel.h"
#include "utils/syscache.h"
/*
* Global context for foreign_expr_walker's search of an expression tree.
*/
typedef struct foreign_glob_cxt
{
PlannerInfo *root; /* global planner state */
RelOptInfo *foreignrel; /* the foreign relation we are planning for */
Relids relids; /* relids of base relations in the underlying
* scan */
bool is_having_cond; /* "true" for HAVING clause condition */
} foreign_glob_cxt;
/*
* Local (per-tree-level) context for foreign_expr_walker's search.
* This is concerned with identifying collations used in the expression.
*/
typedef enum
{
FDW_COLLATE_NONE, /* expression is of a noncollatable type */
FDW_COLLATE_SAFE, /* collation derives from a foreign Var */
FDW_COLLATE_UNSAFE /* collation derives from something else */
} FDWCollateState;
typedef struct foreign_loc_cxt
{
Oid collation; /* OID of current collation, if any */
FDWCollateState state; /* state of current collation choice */
} foreign_loc_cxt;
/* Local functions forward declarations */
static bool foreign_expr_walker(Node *node,
foreign_glob_cxt *glob_cxt,
foreign_loc_cxt *outer_cxt);
static List *prepare_var_list_for_baserel(Oid relid, Index varno,
Bitmapset *attrs_used);
static HTAB *column_info_hash(List *colname_list, List *colnum_list,
List *rti_list, List *isouter_list);
static void mongo_prepare_pipeline(List *clause, BSON *inner_pipeline,
pipeline_cxt *context);
static void mongo_append_clauses_to_pipeline(List *clause, BSON *child_doc,
pipeline_cxt *context);
#if PG_VERSION_NUM >= 160000
static List *mongo_append_unique_var(List *varlist, Var *var);
#endif
/*
* mongo_query_document
* Takes in the applicable operator expressions for relation, the join
* clauses for join relation, and grouping targets for upper relation and
* converts these expressions, join clauses, and grouping targets into
* equivalent queries in MongoDB.
*
* For join clauses, transforms simple comparison expressions along with a
* comparison between two vars and nested operator expressions as well.
*
* Example: Consider the following two foreign tables:
* t1(_id NAME, age INT, name VARCHAR)
* t2(_id NAME, old INT, alias VARCHAR)
*
* SQL query:
* SELECT * FROM t1 LEFT JOIN t2 ON (t1.age = t2.old)
* WHERE (t1.age % 2) = 1
* ORDER BY t1.age ASC NULLS FIRST;
* Equivalent MongoDB query:
*
* db.t1.aggregate([
* {
* "$lookup":
* {
* "from": "t2",
* "let": { "v_age": "$age" },
* "pipeline": [
* {
* "$match":
* {
* "$expr":
* {
* "$and": [
* { "$eq": [ "$$v_age", "$old" ] }
* { "$ne": [ "$$v_age", null ] },
* { "$ne": [ "$old", null ] },
* ]
* }
* }
* }
* ],
* "as": "Join_Result"
* }
* },
* { "$match" :
* {
* "$expr" :
* { "$and" : [
* { "$eq" : [ { "$mod" : [ "$age", 2] }, 1]},
* { "$ne" : [ "$age", null ] }
* ]
* }
* }
* }
* {
* "$unwind":
* {
* "path": "$Join_Result",
* "preserveNullAndEmptyArrays": true
* }
* },
* { "$sort": { "age" : 1 } }
* ])
*
* Any MongoDB query would have the following three main arrays:
* 1. Root pipeline array (first square bracket):
* This has three elements called $lookup, $unwind, and $match stages.
* 2. Inner pipeline array (starting with "pipeline" keyword above):
* It has one element that is $match.
* 3. "$and" expression inside inner pipeline:
* These elements depend on the join clauses available.
*
* The outer $match stage (2nd element of root pipeline array) represents
* remote_exprs, and $match inside $lookup stage represents the join clauses.
*
* For grouping target, add $group stage on the base relation or join relation.
* The HAVING clause is nothing but a post $match stage.
*
* Example: Consider above table t1:
*
* SQL query:
* SELECT name, SUM(age) FROM t1 GROUP BY name HAVING MIN(name) = 'xyz'
* ORDER BY name DESC NULLS LAST;
*
* Equivalent MongoDB query:
*
* db.t1.aggregate([
* {
* "$group":
* {
* "_id": {"name": "$name"},
* "v_agg0": {"$sum": "$age"},
* "v_having": {"$min": "$name"}
* }
* },
* {
* "$match": {"v_having": "xyz"}
* }
* { "$sort": { "name" : -1 } }
* ])
*
* For ORDER BY, add $sort stage on the base relation or join or grouping
* relation as shown in the above examples of join and grouping relations.
*/
BSON *
mongo_query_document(ForeignScanState *scanStateNode)
{
ForeignScan *fsplan = (ForeignScan *) scanStateNode->ss.ps.plan;
BSON *queryDocument = bsonCreate();
BSON *filter = bsonCreate();
List *PrivateList = fsplan->fdw_private;
List *opExpressionList = list_nth(PrivateList,
mongoFdwPrivateRemoteExprList);
MongoFdwModifyState *fmstate = (MongoFdwModifyState *) scanStateNode->fdw_state;
BSON root_pipeline;
BSON match_stage;
int root_index = 0;
List *joinclauses = NIL;
List *colnum_list;
List *colname_list = NIL;
List *isouter_list = NIL;
List *rti_list;
List *pathkey_list;
List *is_ascsort_list;
char *inner_relname = NULL;
char *outer_relname = NULL;
HTAB *columnInfoHash;
int jointype = 0;
bool has_limit;
/* Retrieve data passed by planning phase */
colname_list = list_nth(PrivateList, mongoFdwPrivateJoinClauseColNameList);
colnum_list = list_nth(PrivateList, mongoFdwPrivareJoinClauseColNumList);
rti_list = list_nth(PrivateList, mongoFdwPrivateJoinClauseRtiList);
isouter_list = list_nth(PrivateList, mongoFdwPrivateJoinClauseIsOuterList);
#ifdef USE_ASSERT_CHECKING
{
/* Length should be same for all lists of column information */
int natts = list_length(colname_list);
Assert(natts == list_length(colnum_list) &&
natts == list_length(rti_list) &&
natts == list_length(isouter_list));
}
#endif
/* Store information in the hash-table */
columnInfoHash = column_info_hash(colname_list, colnum_list, rti_list,
isouter_list);
/* Retrieve information related to ORDER BY clause */
pathkey_list = list_nth(PrivateList, mongoFdwPrivatePathKeyList);
is_ascsort_list = list_nth(PrivateList, mongoFdwPrivateIsAscSortList);
/* Retrieve information related to LIMIT/OFFSET clause */
has_limit = intVal(list_nth(PrivateList, mongoFdwPrivateHasLimitClause));
if (fmstate->relType == JOIN_REL || fmstate->relType == UPPER_JOIN_REL)
{
List *innerouter_relname;
joinclauses = list_nth(PrivateList, mongoFdwPrivateJoinClauseList);
if (joinclauses)
jointype = intVal(list_nth(PrivateList, mongoFdwPrivateJoinType));
innerouter_relname = list_nth(PrivateList,
mongoFdwPrivateJoinInnerOuterRelName);
inner_relname = strVal(list_nth(innerouter_relname, 0));
outer_relname = strVal(list_nth(innerouter_relname, 1));
}
/* Prepare array of stages */
bsonAppendStartArray(queryDocument, "pipeline", &root_pipeline);
/*
* Add filter into query pipeline if available. These are remote_exprs
* i.e. clauses available in WHERE and those are push-able to the remote
* side.
*/
if (opExpressionList)
{
pipeline_cxt context;
context.colInfoHash = columnInfoHash;
context.isBoolExpr = false;
context.isJoinClause = false;
context.scanStateNode = scanStateNode;
bsonAppendStartArray(filter, "pipeline", &match_stage);
/* Form equivalent WHERE clauses in MongoDB */
mongo_prepare_pipeline(opExpressionList, &match_stage, &context);
bsonAppendFinishArray(filter, &match_stage);
}
if (fmstate->relType == JOIN_REL || fmstate->relType == UPPER_JOIN_REL)
{
BSON inner_pipeline;
BSON lookup_object;
BSON lookup;
BSON let_exprs;
BSON unwind_stage;
BSON unwind;
BSON *inner_pipeline_doc = bsonCreate();
ListCell *cell1;
ListCell *cell2;
/* $lookup stage. This is to perform JOIN */
bsonAppendStartObject(&root_pipeline, psprintf("%d", root_index++),
&lookup_object);
bsonAppendStartObject(&lookup_object, "$lookup", &lookup);
bsonAppendUTF8(&lookup, "from", inner_relname);
/*
* Start "let" operator: Specifies variables to use in the pipeline
* stages. To access columns of outer relation, those need to be
* defined in terms of a variable using "let".
*/
bsonAppendStartObject(&lookup, "let", &let_exprs);
forboth(cell1, colname_list, cell2, isouter_list)
{
char *colname = strVal(lfirst(cell1));
bool is_outer = lfirst_int(cell2);
/*
* Ignore column name with "*" because this is not the name of any
* particular column and is not allowed in the let operator. While
* deparsing the COUNT(*) aggregation operation, this column name
* is added to lists to maintain the length of column information.
*/
if (is_outer && strcmp(colname, "*") != 0)
{
char *varname = psprintf("%s",
get_varname_for_outer_col(colname));
char *field = psprintf("$%s", colname);
bsonAppendUTF8(&let_exprs, varname, field);
}
}
bsonAppendFinishObject(&lookup, &let_exprs); /* End "let" */
/* Form inner pipeline required in $lookup stage to execute $match */
bsonAppendStartArray(inner_pipeline_doc, "pipeline", &inner_pipeline);
if (joinclauses)
{
pipeline_cxt context;
context.colInfoHash = columnInfoHash;
context.isBoolExpr = false;
context.isJoinClause = true;
context.scanStateNode = scanStateNode;
/* Form equivalent join qual clauses in MongoDB */
mongo_prepare_pipeline(joinclauses, &inner_pipeline, &context);
bsonAppendFinishArray(inner_pipeline_doc, &inner_pipeline);
}
/* Append inner pipeline to $lookup stage */
bson_append_array(&lookup, "pipeline", (int) strlen("pipeline"),
&inner_pipeline);
bsonAppendUTF8(&lookup, "as", "Join_Result");
bsonAppendFinishObject(&lookup_object, &lookup);
bsonAppendFinishObject(&root_pipeline, &lookup_object);
/* $match stage. This is to add a filter */
if (opExpressionList)
bsonAppendBson(&root_pipeline, "$match", &match_stage);
/*
* $unwind stage. This deconstructs an array field from the input
* documents to output a document for each element.
*/
bsonAppendStartObject(&root_pipeline, psprintf("%d", root_index++),
&unwind_stage);
bsonAppendStartObject(&unwind_stage, "$unwind", &unwind);
bsonAppendUTF8(&unwind, "path", "$Join_Result");
if (jointype == JOIN_INNER)
bsonAppendBool(&unwind, "preserveNullAndEmptyArrays", false);
else
bsonAppendBool(&unwind, "preserveNullAndEmptyArrays", true);
bsonAppendFinishObject(&unwind_stage, &unwind);
bsonAppendFinishObject(&root_pipeline, &unwind_stage);
fmstate->outerRelName = outer_relname;
}
else if (opExpressionList)
bsonAppendBson(&root_pipeline, "$match", &match_stage);
/* Add $group stage for upper relation */
if (fmstate->relType == UPPER_JOIN_REL || fmstate->relType == UPPER_REL)
{
List *func_list;
List *agg_col_list;
List *groupby_col_list;
List *having_expr;
BSON groupby_expr;
BSON group_stage;
BSON group_expr;
BSON group;
ListCell *cell1;
ListCell *cell2;
ListCell *cell3;
List *is_having_list;
Index aggIndex = 0;
func_list = list_nth(PrivateList, mongoFdwPrivateAggType);
agg_col_list = list_nth(PrivateList, mongoFdwPrivateAggColList);
groupby_col_list = list_nth(PrivateList, mongoFdwPrivateGroupByColList);
having_expr = list_nth(PrivateList, mongoFdwPrivateHavingExpr);
is_having_list = list_nth(PrivateList, mongoFdwPrivateIsHavingList);
/* $group stage. */
bsonAppendStartObject(&root_pipeline, psprintf("%d", root_index++),
&group_stage);
bsonAppendStartObject(&group_stage, "$group", &group);
/*
* Add columns from the GROUP BY clause in the "_id" field of $group
* stage. In case of aggregation on join result, a column of the
* inner table needs to be accessed by prefixing it using
* "Join_Result", which is been hardcoded.
*/
if (groupby_col_list)
{
ListCell *columnCell;
bsonAppendStartObject(&group, "_id", &groupby_expr);
foreach(columnCell, groupby_col_list)
{
Var *column = (Var *) lfirst(columnCell);
bool found = false;
ColInfoHashKey key;
ColInfoHashEntry *columnInfo;
key.varNo = column->varno;
key.varAttno = column->varattno;
columnInfo = (ColInfoHashEntry *) hash_search(columnInfoHash,
(void *) &key,
HASH_FIND,
&found);
if (found)
{
if (columnInfo->isOuter)
bsonAppendUTF8(&groupby_expr, columnInfo->colName,
psprintf("$%s", columnInfo->colName));
else
bsonAppendUTF8(&groupby_expr, columnInfo->colName,
psprintf("$Join_Result.%s",
columnInfo->colName));
}
}
bsonAppendFinishObject(&group, &groupby_expr); /* End "_id" */
}
else
{
/* If no GROUP BY clause then append null to the _id. */
bsonAppendNull(&group, "_id");
}
/* Add grouping operation */
forthree(cell1, func_list, cell2, agg_col_list, cell3, is_having_list)
{
ColInfoHashKey key;
ColInfoHashEntry *columnInfo;
bool found = false;
char *func_name = strVal(lfirst(cell1));
Var *column = (Var *) lfirst(cell2);
bool is_having_agg = lfirst_int(cell3);
if (is_having_agg)
bsonAppendStartObject(&group, "v_having", &group_expr);
else
bsonAppendStartObject(&group,
psprintf("AGG_RESULT_KEY%d",
aggIndex++),
&group_expr);
key.varNo = column->varno;
key.varAttno = column->varattno;
columnInfo = (ColInfoHashEntry *) hash_search(columnInfoHash,
(void *) &key,
HASH_FIND,
&found);
/*
* The aggregation operation in MongoDB other than COUNT has the
* same name as PostgreSQL but COUNT needs to be performed using
* the $sum operator because MongoDB doesn't have a direct $count
* operator for the currently supported version (i.e. v4.4).
*
* There is no syntax in MongoDB to provide column names for COUNT
* operation but for other supported operations, we can do so.
*
* In case of aggregation over the join, the resulted columns of
* inner relation need to be accessed by prefixing it with
* "Join_Result".
*/
if (found && strcmp(func_name, "count") != 0)
{
if (columnInfo->isOuter)
bsonAppendUTF8(&group_expr, psprintf("$%s", func_name),
psprintf("$%s", columnInfo->colName));
else
bsonAppendUTF8(&group_expr, psprintf("$%s", func_name),
psprintf("$Join_Result.%s",
columnInfo->colName));
}
else
{
/*
* The COUNT(*) in PostgreSQL is equivalent to {$sum: 1} in
* the MongoDB.
*/
bsonAppendInt32(&group_expr, psprintf("$%s", "sum"), 1);
}
bsonAppendFinishObject(&group, &group_expr);
}
bsonAppendFinishObject(&group_stage, &group);
bsonAppendFinishObject(&root_pipeline, &group_stage);
/* Add HAVING operation */
if (having_expr)
{
pipeline_cxt context;
context.colInfoHash = columnInfoHash;
context.isBoolExpr = false;
context.isJoinClause = false;
context.scanStateNode = scanStateNode;
/* $match stage. Add a filter for the HAVING clause */
bsonAppendStartObject(&root_pipeline, psprintf("%d", root_index++),
&match_stage);
/* Form equivalent HAVING clauses in MongoDB */
mongo_prepare_pipeline(having_expr, &match_stage, &context);
bsonAppendFinishObject(&root_pipeline, &match_stage);
}
}
/* Add sort stage */
if (pathkey_list)
{
BSON sort_stage;
BSON sort;
ListCell *cell1;
ListCell *cell2;
bsonAppendStartObject(&root_pipeline, psprintf("%d", root_index++),
&sort_stage);
bsonAppendStartObject(&sort_stage, "$sort", &sort);
forboth(cell1, pathkey_list, cell2, is_ascsort_list)
{
Var *column = (Var *) lfirst(cell1);
int is_asc_sort = lfirst_int(cell2);
bool found = false;
ColInfoHashKey key;
ColInfoHashEntry *columnInfo;
/* Find column name */
key.varNo = column->varno;
key.varAttno = column->varattno;
columnInfo = (ColInfoHashEntry *) hash_search(columnInfoHash,
(void *) &key,
HASH_FIND,
&found);
if (found)
{
/*
* In the case of upper rel, access the column by prefixing it
* with "_id". To access the column of the inner relation in
* the join operation, use the prefix "Join_result" because
* direct access is not possible. However, columns of the
* simple relation and outer relation of the join can be
* accessed directly.
*/
if (fmstate->relType == UPPER_JOIN_REL ||
fmstate->relType == UPPER_REL)
bsonAppendInt32(&sort,
psprintf("_id.%s", columnInfo->colName),
is_asc_sort);
else if (!columnInfo->isOuter && fmstate->relType != BASE_REL)
bsonAppendInt32(&sort,
psprintf("Join_result.%s",
columnInfo->colName),
is_asc_sort);
else
bsonAppendInt32(&sort, columnInfo->colName, is_asc_sort);
}
}
bsonAppendFinishObject(&sort_stage, &sort);
bsonAppendFinishObject(&root_pipeline, &sort_stage); /* End sort */
}
/* Add LIMIT/SKIP stage */
if (has_limit)
{
int64 limit_value;
int64 offset_value;
/*
* Add skip stage for OFFSET clause. However, don't add the same if
* either offset is not provided or the offset value is zero.
*/
offset_value = (int64) intVal(list_nth(PrivateList,
mongoFdwPrivateLimitOffsetList));
if (offset_value != -1 && offset_value != 0)
{
BSON skip_stage;
bsonAppendStartObject(&root_pipeline, psprintf("%d", root_index++),
&skip_stage);
bsonAppendInt64(&skip_stage, "$skip", offset_value);
bsonAppendFinishObject(&root_pipeline, &skip_stage);
}
/*
* Add limit stage for LIMIT clause. However, don't add the same if
* the limit is not provided.
*/
limit_value = (int64) intVal(list_nth(PrivateList,
mongoFdwPrivateLimitCountList));
if (limit_value != -1)
{
BSON limit_stage;
bsonAppendStartObject(&root_pipeline, psprintf("%d", root_index++),
&limit_stage);
bsonAppendInt64(&limit_stage, "$limit", limit_value);
bsonAppendFinishObject(&root_pipeline, &limit_stage);
}
}
bsonAppendFinishArray(queryDocument, &root_pipeline);
return queryDocument;
}
/*
* mongo_operator_name
* Takes in the given PostgreSQL comparison operator name, and returns its
* equivalent in MongoDB.
*/
char *
mongo_operator_name(const char *operatorName)
{
const char *mongoOperatorName = NULL;
const int32 nameCount = 14;
static const char *nameMappings[][2] = {{"<", "$lt"},
{">", "$gt"},
{"<=", "$lte"},
{">=", "$gte"},
{"<>", "$ne"},
{"=", "$eq"},
{"+", "$add"},
{"-", "$subtract"},
{"*", "$multiply"},
{"/", "$divide"},
{"%", "$mod"},
{"^", "$pow"},
{"|/", "$sqrt"},
{"@", "$abs"}};
int32 nameIndex;
for (nameIndex = 0; nameIndex < nameCount; nameIndex++)
{
const char *pgOperatorName = nameMappings[nameIndex][0];
if (strncmp(pgOperatorName, operatorName, NAMEDATALEN) == 0)
{
mongoOperatorName = nameMappings[nameIndex][1];
break;
}
}
return (char *) mongoOperatorName;
}
void
append_param_value(BSON *queryDocument, const char *keyName, Param *paramNode,
ForeignScanState *scanStateNode)
{
ExprState *param_expr;
Datum param_value;
bool isNull;
ExprContext *econtext;
if (scanStateNode == NULL)
return;
econtext = scanStateNode->ss.ps.ps_ExprContext;
/* Prepare for parameter expression evaluation */
param_expr = ExecInitExpr((Expr *) paramNode, (PlanState *) scanStateNode);
/* Evaluate the parameter expression */
param_value = ExecEvalExpr(param_expr, econtext, &isNull);
append_mongo_value(queryDocument, keyName, param_value, isNull,
paramNode->paramtype);
}
/*
* append_constant_value
* Appends to the query document the key name and constant value.
*
* The function translates the constant value from its PostgreSQL type
* to its MongoDB equivalent.
*/
void
append_constant_value(BSON *queryDocument, const char *keyName, Const *constant)
{
if (constant->constisnull)
{
bsonAppendNull(queryDocument, keyName);
return;
}
append_mongo_value(queryDocument, keyName, constant->constvalue, false,
constant->consttype);
}
bool
append_mongo_value(BSON *queryDocument, const char *keyName, Datum value,
bool isnull, Oid id)
{
bool status = false;
if (isnull)
{
status = bsonAppendNull(queryDocument, keyName);
return status;
}
switch (id)
{
case INT2OID:
{
int16 valueInt = DatumGetInt16(value);
status = bsonAppendInt32(queryDocument, keyName,
(int) valueInt);
}
break;
case INT4OID:
{
int32 valueInt = DatumGetInt32(value);
status = bsonAppendInt32(queryDocument, keyName, valueInt);
}
break;
case INT8OID:
{
int64 valueLong = DatumGetInt64(value);
status = bsonAppendInt64(queryDocument, keyName, valueLong);
}
break;
case FLOAT4OID:
{
float4 valueFloat = DatumGetFloat4(value);
status = bsonAppendDouble(queryDocument, keyName,
(double) valueFloat);
}
break;
case FLOAT8OID:
{
float8 valueFloat = DatumGetFloat8(value);
status = bsonAppendDouble(queryDocument, keyName, valueFloat);
}
break;
case NUMERICOID:
{
Datum valueDatum = DirectFunctionCall1(numeric_float8,
value);
float8 valueFloat = DatumGetFloat8(valueDatum);
status = bsonAppendDouble(queryDocument, keyName, valueFloat);
}
break;
case BOOLOID:
{
bool valueBool = DatumGetBool(value);
status = bsonAppendBool(queryDocument, keyName,
(int) valueBool);
}
break;
case BPCHAROID:
case VARCHAROID:
case TEXTOID:
{
char *outputString;
Oid outputFunctionId;
bool typeVarLength;
getTypeOutputInfo(id, &outputFunctionId, &typeVarLength);
outputString = OidOutputFunctionCall(outputFunctionId, value);
status = bsonAppendUTF8(queryDocument, keyName, outputString);
}
break;
case BYTEAOID:
{
int len;
char *data;
char *result = DatumGetPointer(value);
if (VARATT_IS_1B(result))
{
len = VARSIZE_1B(result) - VARHDRSZ_SHORT;
data = VARDATA_1B(result);
}
else
{
len = VARSIZE_4B(result) - VARHDRSZ;
data = VARDATA_4B(result);
}
if (strcmp(keyName, "_id") == 0)
{
bson_oid_t oid;
bson_oid_init_from_data(&oid, (const uint8_t *) data);
status = bsonAppendOid(queryDocument, keyName, &oid);
}
else
status = bsonAppendBinary(queryDocument, keyName, data,
len);
}
break;
case NAMEOID:
{
char *outputString;
Oid outputFunctionId;
bool typeVarLength;
bson_oid_t bsonObjectId;
memset(bsonObjectId.bytes, 0, sizeof(bsonObjectId.bytes));
getTypeOutputInfo(id, &outputFunctionId, &typeVarLength);
outputString = OidOutputFunctionCall(outputFunctionId, value);
bsonOidFromString(&bsonObjectId, outputString);
status = bsonAppendOid(queryDocument, keyName, &bsonObjectId);
}
break;
case DATEOID:
{
Datum valueDatum = DirectFunctionCall1(date_timestamp,
value);
Timestamp valueTimestamp = DatumGetTimestamp(valueDatum);
int64 valueMicroSecs = valueTimestamp + POSTGRES_TO_UNIX_EPOCH_USECS;
int64 valueMilliSecs = valueMicroSecs / 1000;
status = bsonAppendDate(queryDocument, keyName,
valueMilliSecs);
}
break;
case TIMESTAMPOID:
case TIMESTAMPTZOID:
{
Timestamp valueTimestamp = DatumGetTimestamp(value);
int64 valueMicroSecs = valueTimestamp + POSTGRES_TO_UNIX_EPOCH_USECS;
int64 valueMilliSecs = valueMicroSecs / 1000;
status = bsonAppendDate(queryDocument, keyName,
valueMilliSecs);
}
break;
case NUMERICARRAY_OID:
{
ArrayType *array;
Oid elmtype;
int16 elmlen;
bool elmbyval;
char elmalign;
int num_elems;
Datum *elem_values;
bool *elem_nulls;
int i;
BSON childDocument;
array = DatumGetArrayTypeP(value);
elmtype = ARR_ELEMTYPE(array);
get_typlenbyvalalign(elmtype, &elmlen, &elmbyval, &elmalign);
deconstruct_array(array, elmtype, elmlen, elmbyval, elmalign,
&elem_values, &elem_nulls, &num_elems);
bsonAppendStartArray(queryDocument, keyName, &childDocument);
for (i = 0; i < num_elems; i++)
{
Datum valueDatum;
float8 valueFloat;
if (elem_nulls[i])
continue;
valueDatum = DirectFunctionCall1(numeric_float8,
elem_values[i]);
valueFloat = DatumGetFloat8(valueDatum);
status = bsonAppendDouble(&childDocument, keyName,
valueFloat);
}
bsonAppendFinishArray(queryDocument, &childDocument);
pfree(elem_values);
pfree(elem_nulls);
}
break;
case TEXTARRAYOID:
{
ArrayType *array;
Oid elmtype;
int16 elmlen;
bool elmbyval;
char elmalign;
int num_elems;
Datum *elem_values;
bool *elem_nulls;
int i;
BSON childDocument;
array = DatumGetArrayTypeP(value);
elmtype = ARR_ELEMTYPE(array);
get_typlenbyvalalign(elmtype, &elmlen, &elmbyval, &elmalign);
deconstruct_array(array, elmtype, elmlen, elmbyval, elmalign,
&elem_values, &elem_nulls, &num_elems);
bsonAppendStartArray(queryDocument, keyName, &childDocument);
for (i = 0; i < num_elems; i++)
{
char *valueString;
Oid outputFunctionId;
bool typeVarLength;
if (elem_nulls[i])
continue;
getTypeOutputInfo(TEXTOID, &outputFunctionId,
&typeVarLength);
valueString = OidOutputFunctionCall(outputFunctionId,
elem_values[i]);
status = bsonAppendUTF8(&childDocument, keyName,
valueString);
}
bsonAppendFinishArray(queryDocument, &childDocument);
pfree(elem_values);
pfree(elem_nulls);
}
break;
case JSONOID:
{
char *outputString;
Oid outputFunctionId;
struct json_object *o;
bool typeVarLength;
getTypeOutputInfo(id, &outputFunctionId, &typeVarLength);
outputString = OidOutputFunctionCall(outputFunctionId, value);
o = jsonTokenerPrase(outputString);
if (o == NULL)
{
elog(WARNING, "cannot parse the document");
status = 0;
break;
}
status = jsonToBsonAppendElement(queryDocument, keyName, o);
}
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 constant value to BSON value"),
errhint("Constant value data type: %u", id)));
break;
}
return status;
}
/*
* mongo_get_column_list
* Process scan_var_list to find all columns needed for query execution
* and return them.
*
* Also, form two separate lists:
* 1. column_name_list: column names of needed columns.
* 2. is_inner_column_list: column is of inner relation or not.
*/
List *
mongo_get_column_list(PlannerInfo *root, RelOptInfo *foreignrel,
List *scan_var_list, List **column_name_list,
List **is_inner_column_list)
{
List *columnList = NIL;
ListCell *lc;
RelOptInfo *scanrel;
MongoFdwRelationInfo *fpinfo = (MongoFdwRelationInfo *) foreignrel->fdw_private;