forked from pgspider/mongo_fdw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo_query.c
1106 lines (979 loc) · 28.7 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-2021, 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>
#if PG_VERSION_NUM < 120000
#include "access/sysattr.h"
#endif
#if PG_VERSION_NUM >= 120000
#include "access/table.h"
#endif
#include "catalog/heap.h"
#include "catalog/pg_collation.h"
#ifdef META_DRIVER
#include "mongoc.h"
#else
#include "mongo.h"
#endif
#include "mongo_query.h"
#if PG_VERSION_NUM < 120000
#include "nodes/relation.h"
#include "optimizer/var.h"
#endif
#if PG_VERSION_NUM >= 120000
#include "optimizer/optimizer.h"
#endif
#include "parser/parsetree.h"
#include "utils/rel.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 */
unsigned short varcount; /* Var count */
unsigned short opexprcount;
} 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 Expr *FindArgumentOfType(List *argumentList, NodeTag argumentType);
static List *EqualityOperatorList(List *operatorList);
static List *UniqueColumnList(List *operatorList);
static List *ColumnOperatorList(Var *column, List *operatorList);
static void AppendConstantValue(BSON *queryDocument, const char *keyName,
Const *constant);
static void AppendParamValue(BSON *queryDocument, const char *keyName,
Param *paramNode,
ForeignScanState *scanStateNode);
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);
/*
* FindArgumentOfType
* Walks over the given argument list, looks for an argument with the
* given type, and returns the argument if it is found.
*/
static Expr *
FindArgumentOfType(List *argumentList, NodeTag argumentType)
{
Expr *foundArgument = NULL;
ListCell *argumentCell;
foreach(argumentCell, argumentList)
{
Expr *argument = (Expr *) lfirst(argumentCell);
/* For RelabelType type, examine the inner node */
if (IsA(argument, RelabelType))
argument = ((RelabelType *) argument)->arg;
if (nodeTag(argument) == argumentType)
{
foundArgument = argument;
break;
}
}
return foundArgument;
}
/*
* QueryDocument
* Takes in the applicable operator expressions for a relation and
* converts these expressions into equivalent queries in MongoDB.
*
* For now, this function can only transform simple comparison expressions, and
* returns these transformed expressions in a BSON document. For example,
* simple expressions:
* "l_shipdate >= date '1994-01-01' AND l_shipdate < date '1995-01-01'" become
* "l_shipdate: { $gte: new Date(757382400000), $lt: new Date(788918400000) }".
*/
BSON *
QueryDocument(Oid relationId, List *opExpressionList,
ForeignScanState *scanStateNode)
{
List *equalityOperatorList;
List *comparisonOperatorList;
List *columnList;
ListCell *equalityOperatorCell;
ListCell *columnCell;
BSON *queryDocument = BsonCreate();
/*
* We distinguish between equality expressions and others since we need to
* insert the latter (<, >, <=, >=, <>) as separate sub-documents into the
* BSON query object.
*/
equalityOperatorList = EqualityOperatorList(opExpressionList);
comparisonOperatorList = list_difference(opExpressionList,
equalityOperatorList);
/* Append equality expressions to the query */
foreach(equalityOperatorCell, equalityOperatorList)
{
OpExpr *equalityOperator = (OpExpr *) lfirst(equalityOperatorCell);
Oid columnId = InvalidOid;
char *columnName;
Const *constant;
Param *paramNode;
List *argumentList = equalityOperator->args;
Var *column = (Var *) FindArgumentOfType(argumentList, T_Var);
constant = (Const *) FindArgumentOfType(argumentList, T_Const);
paramNode = (Param *) FindArgumentOfType(argumentList, T_Param);
columnId = column->varattno;
#if PG_VERSION_NUM < 110000
columnName = get_relid_attribute_name(relationId, columnId);
#else
columnName = get_attname(relationId, columnId, false);
#endif
if (constant != NULL)
AppendConstantValue(queryDocument, columnName, constant);
else
AppendParamValue(queryDocument, columnName, paramNode,
scanStateNode);
}
/*
* For comparison expressions, we need to group them by their columns and
* append all expressions that correspond to a column as one sub-document.
*
* Otherwise, even when we have two expressions to define the upper- and
* lower-bound of a range, Mongo uses only one of these expressions during
* an index search.
*/
columnList = UniqueColumnList(comparisonOperatorList);
/* Append comparison expressions, grouped by columns, to the query */
foreach(columnCell, columnList)
{
Var *column = (Var *) lfirst(columnCell);
Oid columnId = InvalidOid;
char *columnName;
List *columnOperatorList;
ListCell *columnOperatorCell;
BSON childDocument;
columnId = column->varattno;
#if PG_VERSION_NUM < 110000
columnName = get_relid_attribute_name(relationId, columnId);
#else
columnName = get_attname(relationId, columnId, false);
#endif
/* Find all expressions that correspond to the column */
columnOperatorList = ColumnOperatorList(column,
comparisonOperatorList);
/* For comparison expressions, start a sub-document */
BsonAppendStartObject(queryDocument, columnName, &childDocument);
foreach(columnOperatorCell, columnOperatorList)
{
OpExpr *columnOperator = (OpExpr *) lfirst(columnOperatorCell);
char *operatorName;
char *mongoOperatorName;
List *argumentList = columnOperator->args;
Const *constant = (Const *) FindArgumentOfType(argumentList,
T_Const);
operatorName = get_opname(columnOperator->opno);
mongoOperatorName = MongoOperatorName(operatorName);
#ifdef META_DRIVER
AppendConstantValue(&childDocument, mongoOperatorName, constant);
#else
AppendConstantValue(queryDocument, mongoOperatorName, constant);
#endif
}
BsonAppendFinishObject(queryDocument, &childDocument);
}
if (!BsonFinish(queryDocument))
{
#ifdef META_DRIVER
ereport(ERROR,
(errmsg("could not create document for query"),
errhint("BSON flags: %d", queryDocument->flags)));
#else
ereport(ERROR,
(errmsg("could not create document for query"),
errhint("BSON error: %d", queryDocument->err)));
#endif
}
return queryDocument;
}
/*
* MongoOperatorName
* Takes in the given PostgreSQL comparison operator name, and returns its
* equivalent in MongoDB.
*/
char *
MongoOperatorName(const char *operatorName)
{
const char *mongoOperatorName = NULL;
const int32 nameCount = 5;
static const char *nameMappings[][2] = {{"<", "$lt"},
{">", "$gt"},
{"<=", "$lte"},
{">=", "$gte"},
{"<>", "$ne"}};
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;
}
/*
* EqualityOperatorList
* Finds the equality (=) operators in the given list, and returns these
* operators in a new list.
*/
static List *
EqualityOperatorList(List *operatorList)
{
List *equalityOperatorList = NIL;
ListCell *operatorCell;
foreach(operatorCell, operatorList)
{
OpExpr *operator = (OpExpr *) lfirst(operatorCell);
if (strncmp(get_opname(operator->opno), EQUALITY_OPERATOR_NAME,
NAMEDATALEN) == 0)
equalityOperatorList = lappend(equalityOperatorList, operator);
}
return equalityOperatorList;
}
/*
* UniqueColumnList
* Walks over the given operator list, and extracts the column argument in
* each operator.
*
* The function then de-duplicates extracted columns, and returns them in a new
* list.
*/
static List *
UniqueColumnList(List *operatorList)
{
List *uniqueColumnList = NIL;
ListCell *operatorCell;
foreach(operatorCell, operatorList)
{
OpExpr *operator = (OpExpr *) lfirst(operatorCell);
List *argumentList = operator->args;
Var *column = (Var *) FindArgumentOfType(argumentList, T_Var);
/* List membership is determined via column's equal() function */
uniqueColumnList = list_append_unique(uniqueColumnList, column);
}
return uniqueColumnList;
}
/*
* ColumnOperatorList
* Finds all expressions that correspond to the given column, and returns
* them in a new list.
*/
static List *
ColumnOperatorList(Var *column, List *operatorList)
{
List *columnOperatorList = NIL;
ListCell *operatorCell;
foreach(operatorCell, operatorList)
{
OpExpr *operator = (OpExpr *) lfirst(operatorCell);
List *argumentList = operator->args;
Var *foundColumn = (Var *) FindArgumentOfType(argumentList,
T_Var);
if (equal(column, foundColumn))
columnOperatorList = lappend(columnOperatorList, operator);
}
return columnOperatorList;
}
static void
AppendParamValue(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 */
#if PG_VERSION_NUM >= 100000
param_value = ExecEvalExpr(param_expr, econtext, &isNull);
#else
param_value = ExecEvalExpr(param_expr, econtext, &isNull, NULL);
#endif
AppendMongoValue(queryDocument, keyName, param_value, isNull,
paramNode->paramtype);
}
/*
* AppendConstantValue
* 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.
*/
static void
AppendConstantValue(BSON *queryDocument, const char *keyName, Const *constant)
{
if (constant->constisnull)
{
BsonAppendNull(queryDocument, keyName);
return;
}
AppendMongoValue(queryDocument, keyName, constant->constvalue, false,
constant->consttype);
}
bool
AppendMongoValue(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);
}
#ifdef META_DRIVER
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);
#else
status = BsonAppendBinary(queryDocument, keyName, data, len);
#endif
}
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);
#ifdef META_DRIVER
status = BsonAppendDouble(&childDocument, keyName,
valueFloat);
#else
status = BsonAppendDouble(queryDocument, keyName,
valueFloat);
#endif
}
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(queryDocument, 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.
*/
List *
mongo_get_column_list(PlannerInfo *root, RelOptInfo *foreignrel,
List *scan_var_list)
{
List *columnList = NIL;
ListCell *lc;
foreach(lc, scan_var_list)
{
Var *var = (Var *) lfirst(lc);
Assert(IsA(var, Var));
/* Var belongs to foreign table? */
if (!bms_is_member(var->varno, foreignrel->relids))
continue;
/* Is whole-row reference requested? */
if (var->varattno == 0)
{
List *wr_var_list;
RangeTblEntry *rte = rt_fetch(var->varno, root->parse->rtable);
Bitmapset *attrs_used;
Assert(OidIsValid(rte->relid));
/*
* Get list of Var nodes for all undropped attributes of the base
* relation.
*/
attrs_used = bms_make_singleton(0 -
FirstLowInvalidHeapAttributeNumber);
wr_var_list = prepare_var_list_for_baserel(rte->relid, var->varno,
attrs_used);
columnList = list_concat_unique(columnList, wr_var_list);
bms_free(attrs_used);
}
else
columnList = list_append_unique(columnList, var);
}
return columnList;
}
/*
* Check if expression is safe to execute remotely, and return true if so.
*
* In addition, *outer_cxt is updated with collation information.
*
* We must check that the expression contains only node types we can deparse,
* that all types/operators are safe to send (which we approximate
* as being built-in), and that all collations used in the expression derive
* from Vars of the foreign table.
*
* We only support simple binary operators that compare a column against a
* constant. If the expression is a tree, we don't recurse into it.
*/
static bool
foreign_expr_walker(Node *node, foreign_glob_cxt *glob_cxt,
foreign_loc_cxt *outer_cxt)
{
foreign_loc_cxt inner_cxt;
Oid collation;
FDWCollateState state;
/* Need do nothing for empty subexpressions */
if (node == NULL)
return true;
/* Set up inner_cxt for possible recursion to child nodes */
inner_cxt.collation = InvalidOid;
inner_cxt.state = FDW_COLLATE_NONE;
switch (nodeTag(node))
{
case T_Var:
{
Var *var = (Var *) node;
/* Increment the Var count */
glob_cxt->varcount++;
/*
* If the Var is from the foreign table, we consider its
* collation (if any) safe to use. If it is from another
* table, we treat its collation the same way as we would a
* Param's collation, i.e. it's not safe for it to have a
* non-default collation.
*/
if (var->varno == glob_cxt->foreignrel->relid &&
var->varlevelsup == 0)
{
/* Var belongs to foreign table */
collation = var->varcollid;
state = OidIsValid(collation) ? FDW_COLLATE_SAFE : FDW_COLLATE_NONE;
}
else
{
/* Var belongs to some other table */
collation = var->varcollid;
if (var->varcollid != InvalidOid &&
var->varcollid != DEFAULT_COLLATION_OID)
return false;
if (collation == InvalidOid ||
collation == DEFAULT_COLLATION_OID)
{
/*
* It's noncollatable, or it's safe to combine with a
* collatable foreign Var, so set state to NONE.
*/
state = FDW_COLLATE_NONE;
}
else
{
/*
* Do not fail right away, since the Var might appear
* in a collation-insensitive context.
*/
state = FDW_COLLATE_UNSAFE;
}
}
}
break;
case T_Const:
{
Const *c = (Const *) node;
/*
* We don't push down operators where the constant is an array,
* since conditional operators for arrays in MongoDB aren't
* properly defined.
*/
if (OidIsValid(get_element_type(c->consttype)))
return false;
/*
* If the constant has nondefault collation, either it's of a
* non-builtin type, or it reflects folding of a CollateExpr.
* It's unsafe to send to the remote unless it's used in a
* non-collation-sensitive context.
*/
collation = c->constcollid;
if (collation == InvalidOid ||
collation == DEFAULT_COLLATION_OID)
state = FDW_COLLATE_NONE;
else
state = FDW_COLLATE_UNSAFE;
}
break;
case T_Param:
{
Param *p = (Param *) node;
/*
* Bail out on planner internal params. We could perhaps pass
* them to the remote server as regular params, but we don't
* have the machinery to do that at the moment.
*/
if (p->paramkind != PARAM_EXTERN)
return false;
/*
* Collation rule is same as for Consts and non-foreign Vars.
*/
collation = p->paramcollid;
if (collation == InvalidOid ||
collation == DEFAULT_COLLATION_OID)
state = FDW_COLLATE_NONE;
else
state = FDW_COLLATE_UNSAFE;
}
break;
case T_OpExpr:
{
OpExpr *oe = (OpExpr *) node;
char *oname = get_opname(oe->opno);
/* Increment the operator expression count */
glob_cxt->opexprcount++;
/* We only support =, <, >, <=, >=, and <> operators */
if (!(strncmp(oname, EQUALITY_OPERATOR_NAME, NAMEDATALEN) == 0) &&
(MongoOperatorName(oname) == NULL))
return false;
/*
* Recurse to input subexpressions.
*/
if (glob_cxt->opexprcount > 1 ||
!foreign_expr_walker((Node *) oe->args,
glob_cxt, &inner_cxt))
return false;
/*
* If operator's input collation is not derived from a foreign
* Var, it can't be sent to remote.
*/
if (oe->inputcollid == InvalidOid)
/* OK, inputs are all noncollatable */ ;
else if (inner_cxt.state != FDW_COLLATE_SAFE ||
oe->inputcollid != inner_cxt.collation)
return false;
/* Result-collation handling */
collation = oe->opcollid;
if (collation == InvalidOid)
state = FDW_COLLATE_NONE;
else if (inner_cxt.state == FDW_COLLATE_SAFE &&
collation == inner_cxt.collation)
state = FDW_COLLATE_SAFE;
else if (collation == DEFAULT_COLLATION_OID)
state = FDW_COLLATE_NONE;
else
state = FDW_COLLATE_UNSAFE;
}
break;
case T_RelabelType:
{
RelabelType *r = (RelabelType *) node;
/*
* Recurse to input subexpression.
*/
if (!foreign_expr_walker((Node *) r->arg,
glob_cxt, &inner_cxt))
return false;
/*
* RelabelType must not introduce a collation not derived from
* an input foreign Var (same logic as for a real function).
*/
collation = r->resultcollid;
if (collation == InvalidOid)
state = FDW_COLLATE_NONE;
else if (inner_cxt.state == FDW_COLLATE_SAFE &&
collation == inner_cxt.collation)
state = FDW_COLLATE_SAFE;
else if (collation == DEFAULT_COLLATION_OID)
state = FDW_COLLATE_NONE;
else
state = FDW_COLLATE_UNSAFE;
}
break;
case T_List:
{
List *l = (List *) node;
ListCell *lc;
/*
* Recurse to component subexpressions.
*
* If comparison is between two columns of same table then we
* don't push down because currently building corresponding
* MongoDB query not possible with the help of MongoC driver.
*/
foreach(lc, l)
{
if ((!foreign_expr_walker((Node *) lfirst(lc),
glob_cxt, &inner_cxt)) ||
glob_cxt->varcount > 1)
return false;
}
/*
* When processing a list, collation state just bubbles up
* from the list elements.
*/
collation = inner_cxt.collation;
state = inner_cxt.state;
}
break;
default:
/*
* If it's anything else, assume it's unsafe. This list can be
* expanded later, but don't forget to add deparse support.
*/
return false;
}
/*
* Now, merge my collation information into my parent's state.
*/
if (state > outer_cxt->state)
{
/* Override previous parent state */
outer_cxt->collation = collation;
outer_cxt->state = state;
}
else if (state == outer_cxt->state)
{
/* Merge, or detect error if there's a collation conflict */
switch (state)
{
case FDW_COLLATE_NONE:
/* Nothing + nothing is still nothing */
break;
case FDW_COLLATE_SAFE:
if (collation != outer_cxt->collation)
{
/*
* Non-default collation always beats default.
*/
if (outer_cxt->collation == DEFAULT_COLLATION_OID)
{
/* Override previous parent state */
outer_cxt->collation = collation;
}
else if (collation != DEFAULT_COLLATION_OID)
{
/*
* Conflict; show state as indeterminate. We don't
* want to "return false" right away, since parent
* node might not care about collation.
*/
outer_cxt->state = FDW_COLLATE_UNSAFE;
}