-
Notifications
You must be signed in to change notification settings - Fork 162
/
deparse.c
2538 lines (2223 loc) · 65.7 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-2024, 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_aggregate.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "datatype/timestamp.h"
#include "mysql_fdw.h"
#include "mysql_pushability.h"
#include "nodes/nodeFuncs.h"
#include "nodes/plannodes.h"
#include "optimizer/clauses.h"
#include "optimizer/optimizer.h"
#include "optimizer/prep.h"
#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"
/*
* 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 */
/*
* For join pushdown, only a limited set of operators are allowed to be
* pushed. This flag helps us identify if we are walking through the list
* of join conditions. Also true for aggregate relations to restrict
* aggregates for specified list.
*/
bool is_remote_cond; /* true for join or aggregate relations */
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 */
} 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 is_not_distinct_op; /* True in case of IS NOT DISTINCT clause */
} deparse_expr_cxt;
#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))
/*
* Functions to construct string representation of a node tree.
*/
static void deparseExpr(Expr *expr, 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);
static void mysql_deparse_array_ref(SubscriptingRef *node,
deparse_expr_cxt *context);
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_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, PlannerInfo *root,
Index rtindex, Relation rel,
Bitmapset *attrs_used,
List **retrieved_attrs);
static void mysql_deparse_column_ref(StringInfo buf, int varno, int varattno,
PlannerInfo *root, bool qualify_col);
static void mysql_deparse_select_sql(List *tlist, List **retrieved_attrs,
deparse_expr_cxt *context);
static void mysql_append_conditions(List *exprs, deparse_expr_cxt *context);
static void mysql_deparse_explicit_target_list(List *tlist,
List **retrieved_attrs,
deparse_expr_cxt *context);
static void mysql_deparse_from_expr_for_rel(StringInfo buf, PlannerInfo *root,
RelOptInfo *foreignrel,
bool use_alias, List **param_list);
static void mysql_deparse_from_expr(List *quals, deparse_expr_cxt *context);
static void mysql_append_function_name(Oid funcid, deparse_expr_cxt *context);
static void mysql_deparse_aggref(Aggref *node, deparse_expr_cxt *context);
static void mysql_append_groupby_clause(List *tlist, 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_append_orderby_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_orderby_suffix(Expr *em_expr, const char *sortby_dir,
Oid sortcoltype, bool nulls_first,
deparse_expr_cxt *context);
/*
* Functions to construct string representation of a specific types.
*/
static void deparse_interval(StringInfo buf, Datum datum);
/*
* Local variables.
*/
static char *cur_opname = NULL;
/*
* 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;
}
/*
* mysql_deparse_select_stmt_for_rel
* Deparse SELECT statement for given relation into buf.
*
* tlist contains the list of desired columns to be fetched from foreign
* server. For a base relation fpinfo->attrs_used is used to construct
* SELECT clause, hence the tlist is ignored for a base relation.
*
* remote_conds is the list of conditions to be deparsed into the WHERE clause.
*
* pathkeys is the list of pathkeys to order the result by.
*
* If params_list 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_list is NULL, we're generating the query for EXPLAIN purposes,
* so Params and other-relation Vars should be replaced by dummy values.
*
* List of columns selected is returned in retrieved_attrs.
*/
extern void
mysql_deparse_select_stmt_for_rel(StringInfo buf, PlannerInfo *root,
RelOptInfo *rel, List *tlist,
List *remote_conds, List *pathkeys,
bool has_final_sort, bool has_limit,
List **retrieved_attrs, List **params_list)
{
deparse_expr_cxt context;
List *quals;
MySQLFdwRelationInfo *fpinfo = (MySQLFdwRelationInfo *) rel->fdw_private;
/*
* We handle relations for foreign tables and joins between those and
* upper relations.
*/
Assert(IS_JOIN_REL(rel) || IS_SIMPLE_REL(rel) || IS_UPPER_REL(rel));
/* Fill portions of context common to base relation */
context.buf = buf;
context.root = root;
context.foreignrel = rel;
context.params_list = params_list;
context.scanrel = IS_UPPER_REL(rel) ? fpinfo->outerrel : rel;
context.is_not_distinct_op = false;
/* Construct SELECT clause */
mysql_deparse_select_sql(tlist, retrieved_attrs, &context);
/*
* For upper relations, the WHERE clause is built from the remote
* conditions of the underlying scan relation; otherwise, we can use the
* supplied list of remote conditions directly.
*/
if (IS_UPPER_REL(rel))
{
MySQLFdwRelationInfo *ofpinfo;
ofpinfo = (MySQLFdwRelationInfo *) fpinfo->outerrel->fdw_private;
quals = ofpinfo->remote_conds;
}
else
quals = remote_conds;
/* Construct FROM and WHERE clauses */
mysql_deparse_from_expr(quals, &context);
if (IS_UPPER_REL(rel))
{
/* Append GROUP BY clause */
mysql_append_groupby_clause(fpinfo->grouped_tlist, &context);
/* Append HAVING clause */
if (remote_conds)
{
appendStringInfoString(buf, " HAVING ");
mysql_append_conditions(remote_conds, &context);
}
}
/* Add ORDER BY clause if we found any useful pathkeys */
if (pathkeys)
mysql_append_orderby_clause(pathkeys, has_final_sort, &context);
/* Add LIMIT clause if necessary */
if (has_limit)
mysql_append_limit_clause(&context);
}
/*
* mysql_deparse_select_sql
* Construct a simple SELECT statement that retrieves desired columns
* of the specified foreign table, and append it to "buf". The output
* contains just "SELECT ...".
*
* tlist is the list of desired columns. Read prologue of
* mysql_deparse_select_stmt_for_rel() for details.
*
* We also create an integer List of the columns being retrieved, which is
* returned to *retrieved_attrs.
*/
static void
mysql_deparse_select_sql(List *tlist, List **retrieved_attrs,
deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
RelOptInfo *foreignrel = context->foreignrel;
PlannerInfo *root = context->root;
/*
* Construct SELECT list
*/
appendStringInfoString(buf, "SELECT ");
if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel))
{
/*
* For a join or upper relation the input tlist gives the list of
* columns required to be fetched from the foreign server.
*/
mysql_deparse_explicit_target_list(tlist, retrieved_attrs, context);
}
else
{
RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root);
Relation rel;
MySQLFdwRelationInfo *fpinfo = (MySQLFdwRelationInfo *) foreignrel->fdw_private;
/*
* Core code already has some lock on each rel being planned, so we
* can use NoLock here.
*/
#if PG_VERSION_NUM < 130000
rel = heap_open(rte->relid, NoLock);
#else
rel = table_open(rte->relid, NoLock);
#endif
mysql_deparse_target_list(buf, root, foreignrel->relid, rel,
fpinfo->attrs_used, retrieved_attrs);
#if PG_VERSION_NUM < 130000
heap_close(rel, NoLock);
#else
table_close(rel, NoLock);
#endif
}
}
/*
* mysql_deparse_explicit_target_list
* Deparse given targetlist and append it to context->buf.
*
* retrieved_attrs is the list of continuously increasing integers starting
* from 1. It has same number of entries as tlist.
*/
static void
mysql_deparse_explicit_target_list(List *tlist, List **retrieved_attrs,
deparse_expr_cxt *context)
{
ListCell *lc;
StringInfo buf = context->buf;
int i = 0;
*retrieved_attrs = NIL;
foreach(lc, tlist)
{
if (i > 0)
appendStringInfoString(buf, ", ");
deparseExpr((Expr *) lfirst(lc), context);
*retrieved_attrs = lappend_int(*retrieved_attrs, i + 1);
i++;
}
if (i == 0)
appendStringInfoString(buf, "NULL");
}
/*
* mysql_deparse_from_expr
* Construct a FROM clause and, if needed, a WHERE clause, and
* append those to "buf".
*
* quals is the list of clauses to be included in the WHERE clause.
*/
static void
mysql_deparse_from_expr(List *quals, deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
RelOptInfo *scanrel = context->scanrel;
/* For upper relations, scanrel must be either a joinrel or a baserel */
Assert(!IS_UPPER_REL(context->foreignrel) ||
IS_JOIN_REL(scanrel) || IS_SIMPLE_REL(scanrel));
/* Construct FROM clause */
appendStringInfoString(buf, " FROM ");
mysql_deparse_from_expr_for_rel(buf, context->root, scanrel,
(bms_membership(scanrel->relids) == BMS_MULTIPLE),
context->params_list);
/* Construct WHERE clause */
if (quals != NIL)
{
appendStringInfoString(buf, " WHERE ");
mysql_append_conditions(quals, context);
}
}
/*
* Deparse remote INSERT statement
*/
void
mysql_deparse_insert(StringInfo buf, PlannerInfo *root, Index rtindex,
Relation rel, List *targetAttrs, bool doNothing)
{
ListCell *lc;
#if PG_VERSION_NUM >= 140000
TupleDesc tupdesc = RelationGetDescr(rel);
#endif
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, root, false);
}
appendStringInfoString(buf, ") VALUES (");
pindex = 1;
first = true;
foreach(lc, targetAttrs)
{
if (!first)
appendStringInfoString(buf, ", ");
first = false;
#if PG_VERSION_NUM >= 140000
if (TupleDescAttr(tupdesc, lfirst_int(lc) - 1)->attgenerated)
{
appendStringInfoString(buf, "DEFAULT");
continue;
}
#endif
appendStringInfo(buf, "?");
pindex++;
}
appendStringInfoChar(buf, ')');
}
else
appendStringInfoString(buf, " DEFAULT VALUES");
}
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.
*/
static void
mysql_deparse_target_list(StringInfo buf, PlannerInfo *root, Index rtindex,
Relation rel, Bitmapset *attrs_used,
List **retrieved_attrs)
{
TupleDesc tupdesc = RelationGetDescr(rel);
bool have_wholerow;
bool first;
int i;
/* If there's a whole-row reference, we'll need all the columns. */
have_wholerow = bms_is_member(0 - FirstLowInvalidHeapAttributeNumber,
attrs_used);
first = true;
*retrieved_attrs = NIL;
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, root, false);
*retrieved_attrs = lappend_int(*retrieved_attrs, i);
}
}
/* Don't generate bad syntax if no undropped columns */
if (first)
appendStringInfoString(buf, "NULL");
}
/*
* Construct name to use for given column, and emit it into buf. If it has a
* column_name FDW option, use that instead of attribute name.
*/
static void
mysql_deparse_column_ref(StringInfo buf, int varno, int varattno,
PlannerInfo *root, bool qualify_col)
{
RangeTblEntry *rte;
char *colname = NULL;
List *options;
ListCell *lc;
/* varno must not be any of OUTER_VAR, INNER_VAR and INDEX_VAR. */
Assert(!IS_SPECIAL_VARNO(varno));
/* Get RangeTblEntry from array in PlannerInfo. */
rte = planner_rt_fetch(varno, root);
/*
* If it's a column of a foreign table, and it has the column_name FDW
* option, use that value.
*/
options = GetForeignColumnOptions(rte->relid, varattno);
foreach(lc, options)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, "column_name") == 0)
{
colname = defGetString(def);
break;
}
}
/*
* If it's a column of a regular table or it doesn't have column_name FDW
* option, use attribute name.
*/
if (colname == NULL)
colname = get_attname(rte->relid, varattno, false);
if (qualify_col)
ADD_REL_QUALIFIER(buf, varno);
appendStringInfoString(buf, mysql_quote_identifier(colname, '`'));
}
/*
* Append a SQL string literal representing "val" to buf.
*/
static void
mysql_deparse_string_literal(StringInfo buf, const char *val)
{
const char *valptr;
appendStringInfoChar(buf, '\'');
for (valptr = val; *valptr; valptr++)
{
char ch = *valptr;
if (SQL_STR_DOUBLE(ch, true))
appendStringInfoChar(buf, ch);
appendStringInfoChar(buf, ch);
}
appendStringInfoChar(buf, '\'');
}
/*
* Deparse given expression into context->buf.
*
* This function must support all the same node types that foreign_expr_walker
* accepts.
*
* Note: unlike ruleutils.c, we just use a simple hard-wired parenthesization
* scheme: anything more complex than a Var, Const, function call or cast
* should be self-parenthesized.
*/
static void
deparseExpr(Expr *node, deparse_expr_cxt *context)
{
if (node == NULL)
return;
switch (nodeTag(node))
{
case T_Var:
mysql_deparse_var((Var *) node, context);
break;
case T_Const:
mysql_deparse_const((Const *) node, context);
break;
case T_Param:
mysql_deparse_param((Param *) node, context);
break;
case T_SubscriptingRef:
mysql_deparse_array_ref((SubscriptingRef *) node, context);
break;
case T_FuncExpr:
mysql_deparse_func_expr((FuncExpr *) node, context);
break;
case T_OpExpr:
mysql_deparse_op_expr((OpExpr *) node, context);
break;
case T_DistinctExpr:
mysql_deparse_distinct_expr((DistinctExpr *) node, context);
break;
case T_ScalarArrayOpExpr:
mysql_deparse_scalar_array_op_expr((ScalarArrayOpExpr *) node,
context);
break;
case T_RelabelType:
mysql_deparse_relabel_type((RelabelType *) node, context);
break;
case T_BoolExpr:
mysql_deparse_bool_expr((BoolExpr *) node, context);
break;
case T_NullTest:
mysql_deparse_null_test((NullTest *) node, context);
break;
case T_Aggref:
mysql_deparse_aggref((Aggref *) node, context);
break;
default:
elog(ERROR, "unsupported expression type for deparse: %d",
(int) nodeTag(node));
break;
}
}
/*
* Deparse Interval type into MySQL Interval representation.
*/
static void
deparse_interval(StringInfo buf, Datum datum)
{
struct pg_tm tm;
fsec_t fsec;
bool is_first = true;
#if PG_VERSION_NUM >= 150000
struct pg_itm tt,
*itm = &tt;
#endif
#define append_interval(expr, unit) \
do { \
if (!is_first) \
appendStringInfo(buf, " %s ", cur_opname); \
appendStringInfo(buf, "INTERVAL %d %s", expr, unit); \
is_first = false; \
} while (0)
/* Check saved opname. It could be only "+" and "-" */
Assert(cur_opname);
#if PG_VERSION_NUM >= 150000
interval2itm(*DatumGetIntervalP(datum), itm);
tm.tm_sec = itm->tm_sec;
tm.tm_min = itm->tm_min;
tm.tm_hour = itm->tm_hour;
tm.tm_mday = itm->tm_mday;
tm.tm_mon = itm->tm_mon;
tm.tm_year = itm->tm_year;
fsec = itm->tm_usec;
#else
if (interval2tm(*DatumGetIntervalP(datum), &tm, &fsec) != 0)
elog(ERROR, "could not convert interval to tm");
#endif
if (tm.tm_year > 0)
append_interval(tm.tm_year, "YEAR");
if (tm.tm_mon > 0)
append_interval(tm.tm_mon, "MONTH");
if (tm.tm_mday > 0)
append_interval(tm.tm_mday, "DAY");
if (tm.tm_hour > 0)
append_interval(tm.tm_hour, "HOUR");
if (tm.tm_min > 0)
append_interval(tm.tm_min, "MINUTE");
if (tm.tm_sec > 0)
append_interval(tm.tm_sec, "SECOND");
if (fsec > 0)
{
if (!is_first)
appendStringInfo(buf, " %s ", cur_opname);
#ifdef HAVE_INT64_TIMESTAMP
appendStringInfo(buf, "INTERVAL %d MICROSECOND", fsec);
#else
appendStringInfo(buf, "INTERVAL %f MICROSECOND", fsec);
#endif
}
}
/*
* Deparse remote UPDATE 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.
*/
void
mysql_deparse_update(StringInfo buf, PlannerInfo *root, Index rtindex,
Relation rel, List *targetAttrs, char *attname)
{
AttrNumber pindex;
bool first;
ListCell *lc;
#if PG_VERSION_NUM >= 140000
TupleDesc tupdesc = RelationGetDescr(rel);
#endif
appendStringInfoString(buf, "UPDATE ");
mysql_deparse_relation(buf, rel);
appendStringInfoString(buf, " SET ");
pindex = 2;
first = true;
foreach(lc, targetAttrs)
{
int attnum = lfirst_int(lc);
if (attnum == 1)
continue;
if (!first)
appendStringInfoString(buf, ", ");
first = false;
mysql_deparse_column_ref(buf, rtindex, attnum, root, false);
#if PG_VERSION_NUM >= 140000
if (TupleDescAttr(tupdesc, attnum - 1)->attgenerated)
{
appendStringInfoString(buf, " = DEFAULT");
continue;
}
#endif
appendStringInfo(buf, " = ?");
pindex++;
}
appendStringInfo(buf, " WHERE %s = ?", attname);
}
/*
* Deparse remote DELETE 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.
*/
void
mysql_deparse_delete(StringInfo buf, PlannerInfo *root, Index rtindex,
Relation rel, char *name)
{
appendStringInfoString(buf, "DELETE FROM ");
mysql_deparse_relation(buf, rel);
appendStringInfo(buf, " WHERE %s = ?", name);
}
/*
* Deparse given Var node into context->buf.
*
* If the Var belongs to the foreign relation, just print its remote name.
* Otherwise, it's effectively a Param (and will in fact be a Param at
* run time). Handle it the same way we handle plain Params --- see
* deparseParam for comments.
*/
static void
mysql_deparse_var(Var *node, deparse_expr_cxt *context)
{
Relids relids = context->scanrel->relids;
bool qualify_col;
qualify_col = (bms_membership(relids) == BMS_MULTIPLE);
if (bms_is_member(node->varno, relids) && node->varlevelsup == 0)
{
/* Var belongs to foreign table */
mysql_deparse_column_ref(context->buf, node->varno, node->varattno,
context->root, qualify_col);
}
else
{
/* Treat like a Param */
if (context->params_list)
{
int pindex = 0;
ListCell *lc;
/* Find its index in params_list */
foreach(lc, *context->params_list)
{
pindex++;
if (equal(node, (Node *) lfirst(lc)))
break;
}
if (lc == NULL)
{
/* Not in list, so add it */
pindex++;
*context->params_list = lappend(*context->params_list, node);
}
mysql_print_remote_param(pindex, node->vartype, node->vartypmod,
context);
}
else
mysql_print_remote_placeholder(node->vartype, node->vartypmod,
context);
}
}
/*
* Deparse given constant value into context->buf.
*
* This function has to be kept in sync with ruleutils.c's get_const_expr.
*/
static void
mysql_deparse_const(Const *node, deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
Oid typoutput;
bool typIsVarlena;
char *extval;
if (node->constisnull)
{
appendStringInfoString(buf, "NULL");
return;
}
getTypeOutputInfo(node->consttype, &typoutput, &typIsVarlena);
switch (node->consttype)
{
case INT2OID:
case INT4OID:
case INT8OID:
case OIDOID:
case FLOAT4OID:
case FLOAT8OID:
case NUMERICOID:
{
extval = OidOutputFunctionCall(typoutput, node->constvalue);
/*
* No need to quote unless it's a special value such as 'NaN'.
* See comments in get_const_expr().
*/
if (strspn(extval, "0123456789+-eE.") == strlen(extval))
{
if (extval[0] == '+' || extval[0] == '-')
appendStringInfo(buf, "(%s)", extval);
else
appendStringInfoString(buf, extval);
}
else
appendStringInfo(buf, "'%s'", extval);
}
break;
case BITOID:
case VARBITOID:
extval = OidOutputFunctionCall(typoutput, node->constvalue);
appendStringInfo(buf, "B'%s'", extval);
break;
case BOOLOID:
extval = OidOutputFunctionCall(typoutput, node->constvalue);
if (strcmp(extval, "t") == 0)
appendStringInfoString(buf, "true");
else
appendStringInfoString(buf, "false");
break;
case INTERVALOID:
deparse_interval(buf, node->constvalue);
break;
case BYTEAOID:
/*
* The string for BYTEA always seems to be in the format "\\x##"
* where # is a hex digit, Even if the value passed in is
* 'hi'::bytea we will receive "\x6869". Making this assumption
* allows us to quickly convert postgres escaped strings to mysql
* ones for comparison
*/
extval = OidOutputFunctionCall(typoutput, node->constvalue);
appendStringInfo(buf, "X\'%s\'", extval + 2);
break;
default:
extval = OidOutputFunctionCall(typoutput, node->constvalue);
mysql_deparse_string_literal(buf, extval);
break;
}
}
/*
* Deparse given Param node.
*
* If we're generating the query "for real", add the Param to
* context->params_list if it's not already present, and then use its index
* in that list as the remote parameter number. During EXPLAIN, there's
* no need to identify a parameter number.
*/
static void
mysql_deparse_param(Param *node, deparse_expr_cxt *context)
{
if (context->params_list)
{
int pindex = 0;
ListCell *lc;
/* Find its index in params_list */
foreach(lc, *context->params_list)
{
pindex++;
if (equal(node, (Node *) lfirst(lc)))
break;
}
if (lc == NULL)
{
/* Not in list, so add it */
pindex++;
*context->params_list = lappend(*context->params_list, node);
}
mysql_print_remote_param(pindex, node->paramtype, node->paramtypmod,
context);
}
else
mysql_print_remote_placeholder(node->paramtype, node->paramtypmod,
context);
}
/*
* Deparse an array subscript expression.
*/
static void