forked from EnterpriseDB/mysql_fdw
-
Notifications
You must be signed in to change notification settings - Fork 5
/
deparse.c
6446 lines (5671 loc) · 166 KB
/
deparse.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
/*-------------------------------------------------------------------------
*
* deparse.c
* Query deparser for mysql_fdw
*
* Portions Copyright (c) 2012-2014, PostgreSQL Global Development Group
* Portions Copyright (c) 2004-2022, EnterpriseDB Corporation.
*
* IDENTIFICATION
* deparse.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/transam.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_opfamily.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "catalog/pg_aggregate.h"
#include "datatype/timestamp.h"
#include "mysql_fdw.h"
#include "nodes/nodeFuncs.h"
#include "nodes/plannodes.h"
#include "optimizer/clauses.h"
#include "optimizer/prep.h"
#if PG_VERSION_NUM < 120000
#include "optimizer/var.h"
#else
#include "optimizer/optimizer.h"
#endif
#include "optimizer/tlist.h"
#include "parser/parsetree.h"
#include "pgtime.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/timestamp.h"
#include "utils/typcache.h"
#include "common/keywords.h"
/* Return true if integer type */
#define IS_INTEGER_TYPE(typid) ((typid == INT2OID) || (typid == INT4OID) || (typid == INT8OID))
static bool mysql_contain_functions_walker(Node *node, void *context);
/*
* 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 */
} 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 */
bool can_skip_cast; /* outer function can skip numeric cast */
bool op_flag; /* operator can be pushed down or not */
bool can_pushdown_function; /* true if query contains function
* which can pushed down to remote
* server */
bool can_use_outercast; /* true if inner function accept outer
* cast */
} foreign_loc_cxt;
/*
* Context for deparseExpr
*/
typedef struct deparse_expr_cxt
{
PlannerInfo *root; /* global planner state */
RelOptInfo *foreignrel; /* the foreign relation we are planning for */
RelOptInfo *scanrel; /* the underlying scan relation. Same as
* foreignrel, when that represents a join or
* a base relation. */
StringInfo buf; /* output buffer to append to */
List **params_list; /* exprs that will become remote Params */
bool can_skip_cast; /* outer function can skip numeric cast
* function */
bool can_convert_time; /* time interval need to be converted to
* second */
bool is_not_distinct_op; /* check operator is IS NOT DISTINCT or IS
* DISTINCT */
bool is_not_add_array; /* check if function has variadic argument
* so will not add ARRAY[] */
bool can_convert_unit_arg; /* time interval need to be converted
* to Unit Arguments of Mysql. */
bool can_skip_convert_unit_arg; /* outer function can skip time
* interval cast function */
Oid return_type; /* return type Oid of outer cast function */
FuncExpr *json_table_expr; /* for json_table function */
} deparse_expr_cxt;
typedef struct pull_func_clause_context
{
List *funclist;
} pull_func_clause_context;
typedef struct mysql_default_const_ctx
{
Const *c;
} mysql_default_const_ctx;
#define REL_ALIAS_PREFIX "r"
/* Handy macro to add relation name qualification */
#define ADD_REL_QUALIFIER(buf, varno) \
appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno))
#define SUBQUERY_REL_ALIAS_PREFIX "s"
#define SUBQUERY_COL_ALIAS_PREFIX "c"
/*
* Functions to construct string representation of a node tree.
*/
static void deparseExpr(Expr *expr, deparse_expr_cxt *context);
static void mysql_deparse_from_expr(List *quals, deparse_expr_cxt *context);
static void mysql_deparse_explicit_target_list(List *tlist,
bool is_returning,
List **retrieved_attrs,
deparse_expr_cxt *context);
static void mysql_deparse_select_sql(List *tlist, bool is_subquery, List **retrieved_attrs,
deparse_expr_cxt *context);
static void mysql_deparse_subquery_target_list(deparse_expr_cxt *context);
static void mysql_deparse_locking_clause(deparse_expr_cxt *context);
static void mysql_deparse_from_expr_for_rel(StringInfo buf, PlannerInfo *root,
RelOptInfo *foreignrel, bool use_alias,
Index ignore_rel, List **ignore_conds,
List **params_list);
static void mysql_deparse_range_tbl_ref(StringInfo buf, PlannerInfo *root,
RelOptInfo *foreignrel, bool make_subquery,
Index ignore_rel, List **ignore_conds, List **params_list);
static void mysql_append_conditions(List *exprs, deparse_expr_cxt *context);
static void mysql_deparse_var(Var *node, deparse_expr_cxt *context);
static void mysql_deparse_const(Const *node, deparse_expr_cxt *context);
static void mysql_deparse_param(Param *node, deparse_expr_cxt *context);
#if PG_VERSION_NUM < 120000
static void mysql_deparse_array_ref(ArrayRef * node, deparse_expr_cxt *context);
#else
static void mysql_deparse_subscripting_ref(SubscriptingRef *node,
deparse_expr_cxt *context);
#endif
static void mysql_deparse_func_expr(FuncExpr *node, deparse_expr_cxt *context);
static void mysql_deparse_op_expr(OpExpr *node, deparse_expr_cxt *context);
static void mysql_deparse_operator_name(StringInfo buf,
Form_pg_operator opform);
static void mysql_deparse_distinct_expr(DistinctExpr *node,
deparse_expr_cxt *context);
static void mysql_deparse_scalar_array_op_expr(ScalarArrayOpExpr *node,
deparse_expr_cxt *context);
static void mysql_deparse_relabel_type(RelabelType *node,
deparse_expr_cxt *context);
static void mysql_deparse_bool_expr(BoolExpr *node, deparse_expr_cxt *context);
static void mysql_deparse_null_test(NullTest *node, deparse_expr_cxt *context);
static void mysql_deparse_aggref(Aggref *node, deparse_expr_cxt *context);
static void mysql_deparse_array_expr(ArrayExpr *node,
deparse_expr_cxt *context);
static void mysql_print_remote_param(int paramindex, Oid paramtype,
int32 paramtypmod,
deparse_expr_cxt *context);
static void mysql_print_remote_placeholder(Oid paramtype, int32 paramtypmod,
deparse_expr_cxt *context);
static void mysql_deparse_relation(StringInfo buf, Relation rel);
static void mysql_deparse_target_list(StringInfo buf,
RangeTblEntry *rte,
Index rtindex,
Relation rel,
Bitmapset *attrs_used,
bool qualify_col,
List **retrieved_attrs);
static void mysql_deparse_column_ref(StringInfo buf, int varno, int varattno,
RangeTblEntry *rte, bool qualify_col);
static bool mysql_deparse_op_divide(Expr *node, deparse_expr_cxt *context);
static Node *mysql_deparse_sort_group_clause(Index ref, List *tlist, bool force_colno,
deparse_expr_cxt *context);
static void mysql_deparse_row_expr(RowExpr *node, deparse_expr_cxt *context);
/*
* Functions to construct string representation of a specific types.
*/
static void deparse_interval(StringInfo buf, Datum datum);
static void mysql_append_order_by_clause(List *pathkeys, bool has_final_sort,
deparse_expr_cxt *context);
static void mysql_append_limit_clause(deparse_expr_cxt *context);
static void mysql_append_group_by_clause(List *tlist, deparse_expr_cxt *context);
static void mysql_append_function_name(Oid funcid, deparse_expr_cxt *context);
static void mysql_append_time_unit(Const *node, deparse_expr_cxt *context);
static void mysql_append_order_by_suffix(Oid sortop, Oid sortcoltype, bool nulls_first,
deparse_expr_cxt *context);
static void mysql_append_agg_order_by(List *orderList, List *targetList, deparse_expr_cxt *context);
/*
* Helper functions
*/
static bool mysql_is_subquery_var(Var *node, RelOptInfo *foreignrel,
int *relno, int *colno);
static void mysql_get_relation_column_alias_ids(Var *node, RelOptInfo *foreignrel,
int *relno, int *colno);
static bool exist_in_function_list(char *funcname, const char **funclist);
static bool mysql_is_unique_func(Oid funcid, char *in);
static bool mysql_is_supported_builtin_func(Oid funcid, char *in);
static bool starts_with(const char *pre, const char *str);
static char *mysql_deparse_type_name(Oid type_oid, int32 typemod);
static void mysql_deconstruct_constant_array(Const *node, bool **elem_nulls,
Datum **elem_values, Oid *elmtype, int *num_elems);
static bool mysql_pull_func_clause_walker(Node *node, pull_func_clause_context * context);
static void mysql_deparse_const_array(Const *node, deparse_expr_cxt *context);
static void mysql_deparse_target_json_table_func(FuncExpr *node, deparse_expr_cxt *context);
static void mysql_append_json_table_func(FuncExpr *node, deparse_expr_cxt *context);
static void mysql_append_json_value_func(FuncExpr *node, deparse_expr_cxt *context);
static void mysql_append_memberof_func(FuncExpr *node, deparse_expr_cxt *context);
static void mysql_append_convert_function(FuncExpr *node, deparse_expr_cxt *context);
static void mysql_deparse_numeric_cast(FuncExpr *node, deparse_expr_cxt *context);
static void mysql_deparse_string_cast(FuncExpr *node, deparse_expr_cxt *context, char *proname);
static void mysql_deparse_datetime_cast(FuncExpr *node, deparse_expr_cxt *context, char *proname);
static void mysql_deparse_func_expr_match_against(FuncExpr *node, deparse_expr_cxt *context,
StringInfo buf, char *proname);
static void mysql_deparse_func_expr_position(FuncExpr *node, deparse_expr_cxt *context,
StringInfo buf, char *proname);
static void mysql_deparse_func_expr_trim(FuncExpr *node, deparse_expr_cxt *context,
StringInfo buf, char *proname, char *origin_function);
static void mysql_deparse_func_expr_weight_string(FuncExpr *node, deparse_expr_cxt *context,
StringInfo buf, char *proname);
static void interval2unit(Datum datum, char **expr, char **unit);
static char *mysql_print_type_modifier(char *typname, Oid type_oid, int32 typmod, Oid typmodout);
/*
* Local variables.
*/
static char *cur_opname = NULL;
/*
* MysqlUniqueNumericFunction
* List of unique numeric functions for MySQL
*/
static const char *MysqlUniqueNumericFunction[] = {
"atan",
"conv",
"crc32",
"log2",
"match_against",
"mysql_pi",
"rand",
"truncate",
NULL};
/*
* MysqlUniqueJsonFunction
* List of unique json functions for MySQL
*/
static const char *MysqlUniqueJsonFunction[] = {
"json_array_append",
"json_array_insert",
"json_contains",
"json_contains_path",
"json_depth",
"json_extract",
"json_insert",
"json_keys",
"json_length",
"json_merge",
"json_merge_patch",
"json_merge_preserve",
"json_overlaps",
"json_pretty",
"json_quote",
"json_remove",
"json_replace",
"json_schema_valid",
"json_schema_validation_report",
"json_search",
"json_set",
"json_storage_free",
"json_storage_size",
"mysql_json_table",
"json_type",
"json_unquote",
"json_valid",
"mysql_json_value",
"member_of",
NULL};
/*
* MysqlUniqueStringFunction
* List of unique string function for MySQL
*/
static const char *MysqlUniqueStringFunction[] = {
"bin",
"mysql_char",
"elt",
"export_set",
"field",
"find_in_set",
"mysql_format",
"from_base64",
"hex",
"insert",
"instr",
"lcase",
"locate",
"make_set",
"mid",
"oct",
"ord",
"quote",
"mysql_regexp_instr",
"mysql_regexp_substr",
"mysql_regexp_replace",
"mysql_regexp_like",
"space",
"strcmp",
"substring_index",
"to_base64",
"ucase",
"unhex",
"weight_string",
NULL};
/*
* MysqlUniqueDateTimeFunction
* List of unique Date/Time function for MySQL
* For date_add, Postgres also supports this function with the
* same name but different arguments and return type. So, keep
* it in this list to only push down date_add stub function, not
* push down built-in date_add.
*/
static const char *MysqlUniqueDateTimeFunction[] = {
"adddate",
"addtime",
"convert_tz",
"curdate",
"mysql_current_date",
"curtime",
"mysql_current_time",
"mysql_current_timestamp",
"date_add",
"date_format",
"date_sub",
"datediff",
"day",
"dayname",
"dayofmonth",
"dayofweek",
"dayofyear",
"mysql_extract",
"from_days",
"from_unixtime",
"get_format",
"hour",
"last_day",
"mysql_localtime",
"mysql_localtimestamp",
"makedate",
"maketime",
"microsecond",
"minute",
"month",
"monthname",
"mysql_now",
"period_add",
"period_diff",
"quarter",
"sec_to_time",
"second",
"str_to_date",
"subdate",
"subtime",
"sysdate",
"mysql_time",
"time_format",
"time_to_sec",
"timediff",
"mysql_timestamp",
"timestampadd",
"timestampdiff",
"to_days",
"to_seconds",
"unix_timestamp",
"utc_date",
"utc_time",
"utc_timestamp",
"week",
"weekday",
"weekofyear",
"year",
"yearweek",
NULL};
/*
* MysqlSupportedBuiltinDateTimeFunction
* List of supported date time function for MySQL
*/
static const char *MysqlSupportedBuiltinDateTimeFunction[] = {
"date",
NULL};
/*
* MysqlSupportedBuiltinNumericFunction
* List of supported builtin numeric functions for MySQL
*/
static const char *MysqlSupportedBuiltinNumericFunction[] = {
"abs",
"acos",
"asin",
"atan",
"atan2",
"ceil",
"ceiling",
"cos",
"cot",
"degrees",
"div",
"exp",
"floor",
"ln",
"log",
"log10",
"mod",
"pow",
"power",
"radians",
"round",
"sign",
"sin",
"sqrt",
"tan",
NULL};
/*
* MysqlSupportedBuiltinJsonFunction
* List of supported builtin json functions for MySQL
*/
static const char *MysqlSupportedBuiltinJsonFunction[] = {
"json_build_array",
"json_build_object",
NULL};
/*
* MysqlSupportedBuiltinAggFunction
* List of supported builtin aggregate functions for MySQL
*/
static const char *MysqlSupportedBuiltinAggFunction[] = {
/* aggregate functions */
"sum",
"avg",
"max",
"min",
"bit_and",
"bit_or",
"stddev",
"stddev_pop",
"stddev_samp",
"var_pop",
"var_samp",
"variance",
"count",
NULL};
/*
* MysqlUniqueAggFunction
* List of unique aggregate function for MySQL
*/
static const char *MysqlUniqueAggFunction[] = {
"bit_xor",
"group_concat",
"json_arrayagg",
"json_objectagg",
"std",
NULL};
/*
* MysqlSupportedBuiltinStringFunction
* List of supported builtin string functions for MySQL
*/
static const char *MysqlSupportedBuiltinStringFunction[] = {
"ascii",
"bit_length",
"btrim",
"char_length",
"character_length",
"concat",
"concat_ws",
"left",
"length",
"lower",
"lpad",
"ltrim",
"octet_length",
"repeat",
"replace",
"reverse",
"right",
"rpad",
"rtrim",
"position",
"substr",
"substring",
"trim",
"upper",
NULL};
/*
* MysqlUniqueCastFunction
* List of supported unique cast functions for MySQL
*/
static const char *MysqlUniqueCastFunction[] = {
"convert",
NULL};
/*
* CastFunction
* List of PostgreSQL cast functions, these functions can be skip cast.
*/
static const char *CastFunction[] = {
"float4",
"float8",
"int2",
"int4",
"int8",
"numeric",
"double precision",
/* string cast */
"bpchar",
"varchar",
/* date time cast */
"time",
"timetz",
"timestamp",
"timestamptz",
"interval",
/* json cast */
"json",
"jsonb",
/* binary cast */
"bytea",
NULL};
/*
* pull_func_clause_walker
*
* Recursively search for functions within a clause.
*/
static bool
mysql_pull_func_clause_walker(Node *node, pull_func_clause_context * context)
{
if (node == NULL)
return false;
if (IsA(node, FuncExpr))
{
context->funclist = lappend(context->funclist, node);
return false;
}
return expression_tree_walker(node, mysql_pull_func_clause_walker,
(void *) context);
}
/*
* pull_func_clause
*
* Pull out function from a clause and then add to target list
*/
List *
mysql_pull_func_clause(Node *node)
{
pull_func_clause_context context;
context.funclist = NIL;
mysql_pull_func_clause_walker(node, &context);
return context.funclist;
}
/*
* Append remote name of specified foreign table to buf. Use value of
* table_name FDW option (if any) instead of relation's name. Similarly,
* schema_name FDW option overrides schema name.
*/
static void
mysql_deparse_relation(StringInfo buf, Relation rel)
{
ForeignTable *table;
const char *nspname = NULL;
const char *relname = NULL;
ListCell *lc;
/* Obtain additional catalog information. */
table = GetForeignTable(RelationGetRelid(rel));
/*
* Use value of FDW options if any, instead of the name of object itself.
*/
foreach(lc, table->options)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, "dbname") == 0)
nspname = defGetString(def);
else if (strcmp(def->defname, "table_name") == 0)
relname = defGetString(def);
}
/*
* Note: we could skip printing the schema name if it's pg_catalog, but
* that doesn't seem worth the trouble.
*/
if (nspname == NULL)
nspname = get_namespace_name(RelationGetNamespace(rel));
if (relname == NULL)
relname = RelationGetRelationName(rel);
appendStringInfo(buf, "%s.%s", mysql_quote_identifier(nspname, '`'),
mysql_quote_identifier(relname, '`'));
}
char *
mysql_quote_identifier(const char *str, char quotechar)
{
char *result = palloc(strlen(str) * 2 + 3);
char *res = result;
*res++ = quotechar;
while (*str)
{
if (*str == quotechar)
*res++ = *str;
*res++ = *str;
str++;
}
*res++ = quotechar;
*res++ = '\0';
return result;
}
/*
* Deparse remote INSERT statement
*
* The statement text is appended to buf, and we also create an integer List
* of the columns being retrieved by RETURNING (if any), which is returned
* to *retrieved_attrs.
*/
#if PG_VERSION_NUM >= 140000
/*
* This also stores end position of the VALUES clause, so that we can rebuild
* an INSERT for a batch of rows later.
*/
void
mysql_deparse_insert(StringInfo buf, RangeTblEntry *rte, Index rtindex,
Relation rel, List *targetAttrs, bool doNothing,
int *values_end_len)
#else
void
mysql_deparse_insert(StringInfo buf, RangeTblEntry *rte, Index rtindex,
Relation rel, List *targetAttrs, bool doNothing)
#endif
{
#if PG_VERSION_NUM >= 140000
TupleDesc tupdesc = RelationGetDescr(rel);
#endif
ListCell *lc;
appendStringInfo(buf, "INSERT %sINTO ", doNothing ? "IGNORE " : "");
mysql_deparse_relation(buf, rel);
if (targetAttrs)
{
AttrNumber pindex;
bool first;
appendStringInfoChar(buf, '(');
first = true;
foreach(lc, targetAttrs)
{
int attnum = lfirst_int(lc);
if (!first)
appendStringInfoString(buf, ", ");
first = false;
mysql_deparse_column_ref(buf, rtindex, attnum, rte, false);
}
appendStringInfoString(buf, ") VALUES (");
pindex = 1;
first = true;
foreach(lc, targetAttrs)
{
#if PG_VERSION_NUM >= 140000
int attnum = lfirst_int(lc);
Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
#endif
if (!first)
appendStringInfoString(buf, ", ");
first = false;
#if PG_VERSION_NUM >= 140000
if (attr->attgenerated)
{
appendStringInfoString(buf, "DEFAULT");
continue;
}
#endif
appendStringInfo(buf, "?");
pindex++;
}
appendStringInfoChar(buf, ')');
}
else
appendStringInfoString(buf, " DEFAULT VALUES");
#if PG_VERSION_NUM >= 140000
*values_end_len = buf->len;
#endif
}
#if PG_VERSION_NUM >= 140000
/*
* rebuild remote INSERT statement
*
* Provided a number of rows in a batch, builds INSERT statement with the
* right number of parameters.
*/
void
mysql_rebuild_insert_sql(StringInfo buf, Relation rel,
char *orig_query, List *target_attrs,
int values_end_len, int num_params,
int num_rows)
{
TupleDesc tupdesc = RelationGetDescr(rel);
int i;
int pindex;
bool first;
ListCell *lc;
/* Make sure the values_end_len is sensible */
Assert((values_end_len > 0) && (values_end_len <= strlen(orig_query)));
/* Copy up to the end of the first record from the original query */
appendBinaryStringInfo(buf, orig_query, values_end_len);
/*
* Add records to VALUES clause (we already have parameters for the first
* row, so start at the right offset).
*/
pindex = num_params + 1;
for (i = 0; i < num_rows; i++)
{
appendStringInfoString(buf, ", (");
first = true;
foreach(lc, target_attrs)
{
#if PG_VERSION_NUM >= 140000
int attnum = lfirst_int(lc);
Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
#endif
if (!first)
appendStringInfoString(buf, ", ");
first = false;
#if PG_VERSION_NUM >= 140000
if (attr->attgenerated)
{
appendStringInfoString(buf, "DEFAULT");
continue;
}
#endif
appendStringInfo(buf, "?");
pindex++;
}
appendStringInfoChar(buf, ')');
}
/* Copy stuff after VALUES clause from the original query */
appendStringInfoString(buf, orig_query + values_end_len);
}
#endif
void
mysql_deparse_analyze(StringInfo sql, char *dbname, char *relname)
{
appendStringInfo(sql, "SELECT");
appendStringInfo(sql, " round(((data_length + index_length)), 2)");
appendStringInfo(sql, " FROM information_schema.TABLES");
appendStringInfo(sql, " WHERE table_schema = '%s' AND table_name = '%s'",
dbname, relname);
}
/*
* Emit a target list that retrieves the columns specified in attrs_used.
* This is used for both SELECT and RETURNING targetlists; the is_returning
* parameter is true only for a RETURNING targetlist.
*
* The tlist text is appended to buf, and we also create an integer List
* of the columns being retrieved, which is returned to *retrieved_attrs.
*
* If qualify_col is true, add relation alias before the column name.
*/
#if PG_VERSION_NUM >= 140000
/*
* Construct a simple "TRUNCATE rel" statement
*/
void
mysql_deparse_truncate_sql(StringInfo buf,
List *rels)
{
ListCell *cell;
appendStringInfoString(buf, "TRUNCATE ");
foreach(cell, rels)
{
Relation rel = lfirst(cell);
if (cell != list_head(rels))
appendStringInfoString(buf, ", ");
mysql_deparse_relation(buf, rel);
}
}
#endif
static void
mysql_deparse_target_list(StringInfo buf,
RangeTblEntry *rte,
Index rtindex,
Relation rel,
Bitmapset *attrs_used,
bool qualify_col,
List **retrieved_attrs)
{
TupleDesc tupdesc = RelationGetDescr(rel);
bool have_wholerow;
bool first;
int i;
*retrieved_attrs = NIL;
/* If there's a whole-row reference, we'll need all the columns. */
have_wholerow = bms_is_member(0 - FirstLowInvalidHeapAttributeNumber,
attrs_used);
first = true;
for (i = 1; i <= tupdesc->natts; i++)
{
Form_pg_attribute attr = TupleDescAttr(tupdesc, i - 1);
/* Ignore dropped attributes. */
if (attr->attisdropped)
continue;
if (have_wholerow ||
bms_is_member(i - FirstLowInvalidHeapAttributeNumber,
attrs_used))
{
if (!first)
appendStringInfoString(buf, ", ");
first = false;
mysql_deparse_column_ref(buf, rtindex, i, rte, qualify_col);
*retrieved_attrs = lappend_int(*retrieved_attrs, i);
}
}
/* Don't generate bad syntax if no undropped columns */
if (first)
appendStringInfoString(buf, "NULL");
}
/*
* Deparse the appropriate locking clause (FOR UPDATE or FOR SHARE) for a
* given relation (context->scanrel).
*/
static void
mysql_deparse_locking_clause(deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
PlannerInfo *root = context->root;
RelOptInfo *rel = context->scanrel;
MySQLFdwRelationInfo *fpinfo = (MySQLFdwRelationInfo *) rel->fdw_private;
int relid = -1;
while ((relid = bms_next_member(rel->relids, relid)) >= 0)
{
/*
* Ignore relation if it appears in a lower subquery. Locking clause
* for such a relation is included in the subquery if necessary.
*/
if (bms_is_member(relid, fpinfo->lower_subquery_rels))
continue;
/*
* Add FOR UPDATE/SHARE if appropriate. We apply locking during the
* initial row fetch, rather than later on as is done for local
* tables. The extra roundtrips involved in trying to duplicate the
* local semantics exactly don't seem worthwhile (see also comments
* for RowMarkType).
*
* Note: because we actually run the query as a cursor, this assumes
* that DECLARE CURSOR ... FOR UPDATE is supported, which it isn't
* before 8.3.
*/
#if PG_VERSION_NUM >= 140000
if (bms_is_member(relid, root->all_result_relids) &&
#else
if (relid == root->parse->resultRelation &&
#endif
(root->parse->commandType == CMD_UPDATE ||
root->parse->commandType == CMD_DELETE))
{
/* Relation is UPDATE/DELETE target, so use FOR UPDATE */
appendStringInfoString(buf, " FOR UPDATE");
/* Add the relation alias if we are here for a join relation */
if (IS_JOIN_REL(rel))
appendStringInfo(buf, " OF %s%d", REL_ALIAS_PREFIX, relid);
}
else
{
PlanRowMark *rc = get_plan_rowmark(root->rowMarks, relid);
if (rc)
{
/*
* Relation is specified as a FOR UPDATE/SHARE target, so
* handle that. (But we could also see LCS_NONE, meaning this
* isn't a target relation after all.)
*
* For now, just ignore any [NO] KEY specification, since (a)
* it's not clear what that means for a remote table that we
* don't have complete information about, and (b) it wouldn't
* work anyway on older remote servers. Likewise, we don't
* worry about NOWAIT.
*/
switch (rc->strength)
{
case LCS_NONE:
/* No locking needed */
break;
case LCS_FORKEYSHARE:
case LCS_FORSHARE:
appendStringInfoString(buf, " FOR SHARE");
break;
case LCS_FORNOKEYUPDATE:
case LCS_FORUPDATE:
appendStringInfoString(buf, " FOR UPDATE");
break;
}
/* Add the relation alias if we are here for a join relation */
if (bms_membership(rel->relids) == BMS_MULTIPLE &&
rc->strength != LCS_NONE)
appendStringInfo(buf, " OF %s%d", REL_ALIAS_PREFIX, relid);
}
}
}
}
/*
* Deparse WHERE clauses in given list of RestrictInfos and append them to buf.
*
* baserel is the foreign table we're planning for.
*
* If no WHERE clause already exists in the buffer, is_first should be true.
*
* If params is not NULL, it receives a list of Params and other-relation Vars
* used in the clauses; these values must be transmitted to the remote server
* as parameter values.
*
* If params is NULL, we're generating the query for EXPLAIN purposes,