-
Notifications
You must be signed in to change notification settings - Fork 162
/
mysql_fdw.c
5045 lines (4400 loc) · 147 KB
/
mysql_fdw.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* mysql_fdw.c
* Foreign-data wrapper for remote MySQL servers
*
* Portions Copyright (c) 2012-2014, PostgreSQL Global Development Group
* Portions Copyright (c) 2004-2024, EnterpriseDB Corporation.
*
* IDENTIFICATION
* mysql_fdw.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
/*
* Must be included before mysql.h as it has some conflicting definitions like
* list_length, etc.
*/
#include "mysql_fdw.h"
#include <dlfcn.h>
#include <errmsg.h>
#include <mysql.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/reloptions.h"
#include "access/table.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "catalog/heap.h"
#include "catalog/pg_type.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#include "mysql_pushability.h"
#include "mysql_query.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/nodes.h"
#if PG_VERSION_NUM >= 140000
#include "optimizer/appendinfo.h"
#endif
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/planmain.h"
#include "optimizer/optimizer.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/tlist.h"
#include "parser/parsetree.h"
#if PG_VERSION_NUM >= 160000
#include "parser/parse_relation.h"
#endif
#include "storage/ipc.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/regproc.h"
#include "utils/selfuncs.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
/* Declarations for dynamic loading */
PG_MODULE_MAGIC;
int ((mysql_options) (MYSQL *mysql, enum mysql_option option,
const void *arg));
int ((mysql_stmt_prepare) (MYSQL_STMT *stmt, const char *query,
unsigned long length));
int ((mysql_stmt_execute) (MYSQL_STMT *stmt));
int ((mysql_stmt_fetch) (MYSQL_STMT *stmt));
int ((mysql_query) (MYSQL *mysql, const char *q));
bool ((mysql_stmt_attr_set) (MYSQL_STMT *stmt,
enum enum_stmt_attr_type attr_type,
const void *attr));
bool ((mysql_stmt_close) (MYSQL_STMT *stmt));
bool ((mysql_stmt_reset) (MYSQL_STMT *stmt));
bool ((mysql_free_result) (MYSQL_RES *result));
bool ((mysql_stmt_bind_param) (MYSQL_STMT *stmt, MYSQL_BIND *bnd));
bool ((mysql_stmt_bind_result) (MYSQL_STMT *stmt, MYSQL_BIND *bnd));
MYSQL_STMT *((mysql_stmt_init) (MYSQL *mysql));
MYSQL_RES *((mysql_stmt_result_metadata) (MYSQL_STMT *stmt));
int ((mysql_stmt_store_result) (MYSQL_STMT *stmt));
MYSQL_ROW((mysql_fetch_row) (MYSQL_RES *result));
MYSQL_FIELD *((mysql_fetch_field) (MYSQL_RES *result));
MYSQL_FIELD *((mysql_fetch_fields) (MYSQL_RES *result));
const char *((mysql_error) (MYSQL *mysql));
void ((mysql_close) (MYSQL *sock));
MYSQL_RES *((mysql_store_result) (MYSQL *mysql));
MYSQL *((mysql_init) (MYSQL *mysql));
bool ((mysql_ssl_set) (MYSQL *mysql, const char *key, const char *cert,
const char *ca, const char *capath,
const char *cipher));
MYSQL *((mysql_real_connect) (MYSQL *mysql, const char *host, const char *user,
const char *passwd, const char *db,
unsigned int port, const char *unix_socket,
unsigned long clientflag));
const char *((mysql_get_host_info) (MYSQL *mysql));
const char *((mysql_get_server_info) (MYSQL *mysql));
int ((mysql_get_proto_info) (MYSQL *mysql));
unsigned int ((mysql_stmt_errno) (MYSQL_STMT *stmt));
unsigned int ((mysql_errno) (MYSQL *mysql));
unsigned int ((mysql_num_fields) (MYSQL_RES *result));
unsigned int ((mysql_num_rows) (MYSQL_RES *result));
#define DEFAULTE_NUM_ROWS 1000
/*
* In PG 9.5.1 the number will be 90501,
* our version is 2.9.2 so number will be 20902
*/
#define CODE_VERSION 20902
/*
* The number of rows in a foreign relation are estimated to be so less that
* an in-memory sort on those many rows wouldn't cost noticeably higher than
* the underlying scan. Hence for now, cost sorts same as underlying scans.
*/
#define DEFAULT_MYSQL_SORT_MULTIPLIER 1
/*
* Indexes of FDW-private information stored in fdw_private lists.
*
* These items are indexed with the enum mysqlFdwScanPrivateIndex, so an item
* can be fetched with list_nth(). For example, to get the SELECT statement:
* sql = strVal(list_nth(fdw_private, mysqlFdwScanPrivateSelectSql));
*/
enum mysqlFdwScanPrivateIndex
{
/* SQL statement to execute remotely (as a String node) */
mysqlFdwScanPrivateSelectSql,
/* Integer list of attribute numbers retrieved by the SELECT */
mysqlFdwScanPrivateRetrievedAttrs,
/*
* String describing join i.e. names of relations being joined and types
* of join, added when the scan is join
*/
mysqlFdwScanPrivateRelations,
/*
* List of Var node lists for constructing the whole-row references of
* base relations involved in pushed down join.
*/
mysqlFdwPrivateWholeRowLists,
/*
* Targetlist representing the result fetched from the foreign server if
* whole-row references are involved.
*/
mysqlFdwPrivateScanTList
};
/*
* This enum describes what's kept in the fdw_private list for a ForeignPath.
* We store:
*
* 1) Boolean flag showing if the remote query has the final sort
* 2) Boolean flag showing if the remote query has the LIMIT clause
*/
enum FdwPathPrivateIndex
{
/* has-final-sort flag (as an integer Value node) */
FdwPathPrivateHasFinalSort,
/* has-limit flag (as an integer Value node) */
FdwPathPrivateHasLimit
};
extern PGDLLEXPORT void _PG_init(void);
extern Datum mysql_fdw_handler(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(mysql_fdw_handler);
PG_FUNCTION_INFO_V1(mysql_fdw_version);
PG_FUNCTION_INFO_V1(mysql_display_pushdown_list);
/*
* FDW callback routines
*/
static void mysqlExplainForeignScan(ForeignScanState *node, ExplainState *es);
static void mysqlBeginForeignScan(ForeignScanState *node, int eflags);
static TupleTableSlot *mysqlIterateForeignScan(ForeignScanState *node);
static void mysqlReScanForeignScan(ForeignScanState *node);
static void mysqlEndForeignScan(ForeignScanState *node);
static List *mysqlPlanForeignModify(PlannerInfo *root, ModifyTable *plan,
Index resultRelation, int subplan_index);
static void mysqlBeginForeignModify(ModifyTableState *mtstate,
ResultRelInfo *resultRelInfo,
List *fdw_private, int subplan_index,
int eflags);
static TupleTableSlot *mysqlExecForeignInsert(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
#if PG_VERSION_NUM >= 140000
static void mysqlAddForeignUpdateTargets(PlannerInfo *root,
Index rtindex,
RangeTblEntry *target_rte,
Relation target_relation);
#else
static void mysqlAddForeignUpdateTargets(Query *parsetree,
RangeTblEntry *target_rte,
Relation target_relation);
#endif
static TupleTableSlot *mysqlExecForeignUpdate(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static TupleTableSlot *mysqlExecForeignDelete(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static void mysqlEndForeignModify(EState *estate,
ResultRelInfo *resultRelInfo);
static void mysqlGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel,
Oid foreigntableid);
static void mysqlGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel,
Oid foreigntableid);
static bool mysqlAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
static ForeignScan *mysqlGetForeignPlan(PlannerInfo *root,
RelOptInfo *foreignrel,
Oid foreigntableid,
ForeignPath *best_path, List *tlist,
List *scan_clauses, Plan *outer_plan);
static void mysqlEstimateCosts(PlannerInfo *root, RelOptInfo *baserel,
Cost *startup_cost, Cost *total_cost,
Oid foreigntableid);
static void mysqlGetForeignJoinPaths(PlannerInfo *root,
RelOptInfo *joinrel,
RelOptInfo *outerrel,
RelOptInfo *innerrel,
JoinType jointype,
JoinPathExtraData *extra);
static bool mysqlRecheckForeignScan(ForeignScanState *node,
TupleTableSlot *slot);
static void mysqlGetForeignUpperPaths(PlannerInfo *root,
UpperRelationKind stage,
RelOptInfo *input_rel,
RelOptInfo *output_rel,
void *extra);
static List *mysqlImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void mysqlBeginForeignInsert(ModifyTableState *mtstate,
ResultRelInfo *resultRelInfo);
static void mysqlEndForeignInsert(EState *estate,
ResultRelInfo *resultRelInfo);
#if PG_VERSION_NUM >= 140000
static void mysqlExecForeignTruncate(List *rels,
DropBehavior behavior,
bool restart_seqs);
#endif
/*
* Helper functions
*/
bool mysql_load_library(void);
static void mysql_fdw_exit(int code, Datum arg);
static bool mysql_is_column_unique(Oid foreigntableid);
static void prepare_query_params(PlanState *node,
List *fdw_exprs,
int numParams,
FmgrInfo **param_flinfo,
List **param_exprs,
const char ***param_values,
Oid **param_types);
static void process_query_params(ExprContext *econtext,
FmgrInfo *param_flinfo,
List *param_exprs,
const char **param_values,
MYSQL_BIND **mysql_bind_buf,
Oid *param_types);
static void bind_stmt_params_and_exec(ForeignScanState *node);
static bool mysql_foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel,
JoinType jointype, RelOptInfo *outerrel,
RelOptInfo *innerrel,
JoinPathExtraData *extra);
static List *mysql_adjust_whole_row_ref(PlannerInfo *root,
List *scan_var_list,
List **whole_row_lists,
Bitmapset *relids);
static List *mysql_build_scan_list_for_baserel(Oid relid, Index varno,
Bitmapset *attrs_used,
List **retrieved_attrs);
static void mysql_build_whole_row_constr_info(MySQLFdwExecState *festate,
TupleDesc tupdesc,
Bitmapset *relids,
int max_relid,
List *whole_row_lists,
List *scan_tlist,
List *fdw_scan_tlist);
static HeapTuple mysql_get_tuple_with_whole_row(MySQLFdwExecState *festate,
Datum *values, bool *nulls);
static HeapTuple mysql_form_whole_row(MySQLWRState *wr_state, Datum *values,
bool *nulls);
static bool mysql_foreign_grouping_ok(PlannerInfo *root,
RelOptInfo *grouped_rel,
Node *havingQual);
static void mysql_add_foreign_grouping_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *grouped_rel,
GroupPathExtraData *extra);
static List *mysql_get_useful_ecs_for_relation(PlannerInfo *root,
RelOptInfo *rel);
static List *mysql_get_useful_pathkeys_for_relation(PlannerInfo *root,
RelOptInfo *rel);
#if PG_VERSION_NUM >= 170000
static void mysql_add_paths_with_pathkeys(PlannerInfo *root,
RelOptInfo *rel,
Path *epq_path,
Cost base_startup_cost,
Cost base_total_cost,
List *restrictlist);
#else
static void mysql_add_paths_with_pathkeys(PlannerInfo *root,
RelOptInfo *rel,
Path *epq_path,
Cost base_startup_cost,
Cost base_total_cost);
#endif
static void mysql_add_foreign_ordered_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *ordered_rel);
static void mysql_add_foreign_final_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *final_rel,
FinalPathExtraData *extra);
#if PG_VERSION_NUM >= 160000
static TargetEntry *mysql_tlist_member_match_var(Var *var, List *targetlist);
static List *mysql_varlist_append_unique_var(List *varlist, Var *var);
#endif
void *mysql_dll_handle = NULL;
static int wait_timeout = WAIT_TIMEOUT;
static int interactive_timeout = INTERACTIVE_TIMEOUT;
static void mysql_error_print(MYSQL *conn);
static void mysql_stmt_error_print(MySQLFdwExecState *festate,
const char *msg);
static List *getUpdateTargetAttrs(PlannerInfo *root, RangeTblEntry *rte);
#if PG_VERSION_NUM >= 140000
static char *mysql_remove_quotes(char *s1);
#endif
/*
* mysql_load_library function dynamically load the mysql's library
* libmysqlclient.so. The only reason to load the library using dlopen
* is that, mysql and postgres both have function with same name like
* "list_delete", "list_delete" and "list_free" which cause compiler
* error "duplicate function name" and erroneously linking with a function.
* This port of the code is used to avoid the compiler error.
*
* #define list_delete mysql_list_delete
* #include <mysql.h>
* #undef list_delete
*
* But system crashed on function mysql_stmt_close function because
* mysql_stmt_close internally calling "list_delete" function which
* wrongly binds to postgres' "list_delete" function.
*
* The dlopen function provides a parameter "RTLD_DEEPBIND" which
* solved the binding issue.
*
* RTLD_DEEPBIND:
* Place the lookup scope of the symbols in this library ahead of the
* global scope. This means that a self-contained library will use its
* own symbols in preference to global symbols with the same name contained
* in libraries that have already been loaded.
*/
bool
mysql_load_library(void)
{
#if defined(__APPLE__) || defined(__FreeBSD__)
/*
* Mac OS/BSD does not support RTLD_DEEPBIND, but it still works without
* the RTLD_DEEPBIND
*/
mysql_dll_handle = dlopen(_MYSQL_LIBNAME, RTLD_LAZY);
#else
mysql_dll_handle = dlopen(_MYSQL_LIBNAME, RTLD_LAZY | RTLD_DEEPBIND);
#endif
if (mysql_dll_handle == NULL)
return false;
_mysql_stmt_bind_param = dlsym(mysql_dll_handle, "mysql_stmt_bind_param");
_mysql_stmt_bind_result = dlsym(mysql_dll_handle, "mysql_stmt_bind_result");
_mysql_stmt_init = dlsym(mysql_dll_handle, "mysql_stmt_init");
_mysql_stmt_prepare = dlsym(mysql_dll_handle, "mysql_stmt_prepare");
_mysql_stmt_execute = dlsym(mysql_dll_handle, "mysql_stmt_execute");
_mysql_stmt_fetch = dlsym(mysql_dll_handle, "mysql_stmt_fetch");
_mysql_query = dlsym(mysql_dll_handle, "mysql_query");
_mysql_stmt_result_metadata = dlsym(mysql_dll_handle, "mysql_stmt_result_metadata");
_mysql_stmt_store_result = dlsym(mysql_dll_handle, "mysql_stmt_store_result");
_mysql_fetch_row = dlsym(mysql_dll_handle, "mysql_fetch_row");
_mysql_fetch_field = dlsym(mysql_dll_handle, "mysql_fetch_field");
_mysql_fetch_fields = dlsym(mysql_dll_handle, "mysql_fetch_fields");
_mysql_stmt_close = dlsym(mysql_dll_handle, "mysql_stmt_close");
_mysql_stmt_reset = dlsym(mysql_dll_handle, "mysql_stmt_reset");
_mysql_free_result = dlsym(mysql_dll_handle, "mysql_free_result");
_mysql_error = dlsym(mysql_dll_handle, "mysql_error");
_mysql_options = dlsym(mysql_dll_handle, "mysql_options");
_mysql_ssl_set = dlsym(mysql_dll_handle, "mysql_ssl_set");
_mysql_real_connect = dlsym(mysql_dll_handle, "mysql_real_connect");
_mysql_close = dlsym(mysql_dll_handle, "mysql_close");
_mysql_init = dlsym(mysql_dll_handle, "mysql_init");
_mysql_stmt_attr_set = dlsym(mysql_dll_handle, "mysql_stmt_attr_set");
_mysql_store_result = dlsym(mysql_dll_handle, "mysql_store_result");
_mysql_stmt_errno = dlsym(mysql_dll_handle, "mysql_stmt_errno");
_mysql_errno = dlsym(mysql_dll_handle, "mysql_errno");
_mysql_num_fields = dlsym(mysql_dll_handle, "mysql_num_fields");
_mysql_num_rows = dlsym(mysql_dll_handle, "mysql_num_rows");
_mysql_get_host_info = dlsym(mysql_dll_handle, "mysql_get_host_info");
_mysql_get_server_info = dlsym(mysql_dll_handle, "mysql_get_server_info");
_mysql_get_proto_info = dlsym(mysql_dll_handle, "mysql_get_proto_info");
if (_mysql_stmt_bind_param == NULL ||
_mysql_stmt_bind_result == NULL ||
_mysql_stmt_init == NULL ||
_mysql_stmt_prepare == NULL ||
_mysql_stmt_execute == NULL ||
_mysql_stmt_fetch == NULL ||
_mysql_query == NULL ||
_mysql_stmt_result_metadata == NULL ||
_mysql_stmt_store_result == NULL ||
_mysql_fetch_row == NULL ||
_mysql_fetch_field == NULL ||
_mysql_fetch_fields == NULL ||
_mysql_stmt_close == NULL ||
_mysql_stmt_reset == NULL ||
_mysql_free_result == NULL ||
_mysql_error == NULL ||
_mysql_options == NULL ||
_mysql_ssl_set == NULL ||
_mysql_real_connect == NULL ||
_mysql_close == NULL ||
_mysql_init == NULL ||
_mysql_stmt_attr_set == NULL ||
_mysql_store_result == NULL ||
_mysql_stmt_errno == NULL ||
_mysql_errno == NULL ||
_mysql_num_fields == NULL ||
_mysql_num_rows == NULL ||
_mysql_get_host_info == NULL ||
_mysql_get_server_info == NULL ||
_mysql_get_proto_info == NULL)
return false;
return true;
}
/*
* Library load-time initialization, sets on_proc_exit() callback for
* backend shutdown.
*/
void
_PG_init(void)
{
if (!mysql_load_library())
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("failed to load the mysql query: \n%s", dlerror()),
errhint("Export LD_LIBRARY_PATH to locate the library.")));
DefineCustomIntVariable("mysql_fdw.wait_timeout",
"Server-side wait_timeout",
"Set the maximum wait_timeout"
"use to set the MySQL session timeout",
&wait_timeout,
WAIT_TIMEOUT,
0,
INT_MAX,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
DefineCustomIntVariable("mysql_fdw.interactive_timeout",
"Server-side interactive timeout",
"Set the maximum interactive timeout"
"use to set the MySQL session timeout",
&interactive_timeout,
INTERACTIVE_TIMEOUT,
0,
INT_MAX,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
on_proc_exit(&mysql_fdw_exit, PointerGetDatum(NULL));
}
/*
* mysql_fdw_exit
* Exit callback function.
*/
static void
mysql_fdw_exit(int code, Datum arg)
{
mysql_cleanup_connection();
}
/*
* Foreign-data wrapper handler function: return
* a struct with pointers to my callback routines.
*/
Datum
mysql_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *fdwroutine = makeNode(FdwRoutine);
/* Functions for scanning foreign tables */
fdwroutine->GetForeignRelSize = mysqlGetForeignRelSize;
fdwroutine->GetForeignPaths = mysqlGetForeignPaths;
fdwroutine->GetForeignPlan = mysqlGetForeignPlan;
fdwroutine->BeginForeignScan = mysqlBeginForeignScan;
fdwroutine->IterateForeignScan = mysqlIterateForeignScan;
fdwroutine->ReScanForeignScan = mysqlReScanForeignScan;
fdwroutine->EndForeignScan = mysqlEndForeignScan;
/* Functions for updating foreign tables */
fdwroutine->AddForeignUpdateTargets = mysqlAddForeignUpdateTargets;
fdwroutine->PlanForeignModify = mysqlPlanForeignModify;
fdwroutine->BeginForeignModify = mysqlBeginForeignModify;
fdwroutine->ExecForeignInsert = mysqlExecForeignInsert;
fdwroutine->ExecForeignUpdate = mysqlExecForeignUpdate;
fdwroutine->ExecForeignDelete = mysqlExecForeignDelete;
fdwroutine->EndForeignModify = mysqlEndForeignModify;
/* Function for EvalPlanQual rechecks */
fdwroutine->RecheckForeignScan = mysqlRecheckForeignScan;
/* Support functions for EXPLAIN */
fdwroutine->ExplainForeignScan = mysqlExplainForeignScan;
/* Support functions for ANALYZE */
fdwroutine->AnalyzeForeignTable = mysqlAnalyzeForeignTable;
/* Support functions for IMPORT FOREIGN SCHEMA */
fdwroutine->ImportForeignSchema = mysqlImportForeignSchema;
/* Partition routing and/or COPY from */
fdwroutine->BeginForeignInsert = mysqlBeginForeignInsert;
fdwroutine->EndForeignInsert = mysqlEndForeignInsert;
/* Support functions for join push-down */
fdwroutine->GetForeignJoinPaths = mysqlGetForeignJoinPaths;
/* Support functions for upper relation push-down */
fdwroutine->GetForeignUpperPaths = mysqlGetForeignUpperPaths;
#if PG_VERSION_NUM >= 140000
/* Support function for TRUNCATE */
fdwroutine->ExecForeignTruncate = mysqlExecForeignTruncate;
#endif
PG_RETURN_POINTER(fdwroutine);
}
/*
* mysqlBeginForeignScan
* Initiate access to the database
*/
static void
mysqlBeginForeignScan(ForeignScanState *node, int eflags)
{
TupleTableSlot *tupleSlot = node->ss.ss_ScanTupleSlot;
TupleDesc tupleDescriptor = tupleSlot->tts_tupleDescriptor;
MYSQL *conn;
RangeTblEntry *rte;
MySQLFdwExecState *festate;
EState *estate = node->ss.ps.state;
ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
mysql_opt *options;
ListCell *lc;
int atindex = 0;
unsigned long type = (unsigned long) CURSOR_TYPE_READ_ONLY;
Oid userid;
ForeignServer *server;
UserMapping *user;
ForeignTable *table;
char timeout[255];
int numParams;
int rtindex;
List *fdw_private = fsplan->fdw_private;
char sql_mode[255];
/*
* We'll save private state in node->fdw_state.
*/
festate = (MySQLFdwExecState *) palloc(sizeof(MySQLFdwExecState));
node->fdw_state = (void *) festate;
/*
* If whole-row references are involved in pushed down join extract the
* information required to construct those.
*/
if (list_length(fdw_private) >= mysqlFdwPrivateScanTList)
{
List *whole_row_lists = list_nth(fdw_private,
mysqlFdwPrivateWholeRowLists);
List *scan_tlist = list_nth(fdw_private,
mysqlFdwPrivateScanTList);
TupleDesc scan_tupdesc = ExecTypeFromTL(scan_tlist);
mysql_build_whole_row_constr_info(festate, tupleDescriptor,
fsplan->fs_relids,
list_length(node->ss.ps.state->es_range_table),
whole_row_lists, scan_tlist,
fsplan->fdw_scan_tlist);
/* Change tuple descriptor to match the result from foreign server. */
tupleDescriptor = scan_tupdesc;
}
/*
* Identify which user to do the remote access as. This should match what
* ExecCheckRTEPerms() does. In case of a join use the lowest-numbered
* member RTE as a representative; we would get the same result from any.
*/
if (fsplan->scan.scanrelid > 0)
rtindex = fsplan->scan.scanrelid;
else
#if PG_VERSION_NUM >= 160000
rtindex = bms_next_member(fsplan->fs_base_relids, -1);
#else
rtindex = bms_next_member(fsplan->fs_relids, -1);
#endif
#if PG_VERSION_NUM >= 160000
rte = exec_rt_fetch(rtindex, estate);
userid = fsplan->checkAsUser ? fsplan->checkAsUser : GetUserId();
#else
rte = rt_fetch(rtindex, estate->es_range_table);
userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
#endif
/* Get info about foreign table. */
table = GetForeignTable(rte->relid);
server = GetForeignServer(table->serverid);
user = GetUserMapping(userid, server->serverid);
/* Fetch the options */
options = mysql_get_options(rte->relid, true);
/*
* Get the already connected connection, otherwise connect and get the
* connection handle.
*/
conn = mysql_get_connection(server, user, options);
/* Stash away the state info we have already */
festate->query = strVal(list_nth(fsplan->fdw_private,
mysqlFdwScanPrivateSelectSql));
festate->retrieved_attrs = list_nth(fsplan->fdw_private,
mysqlFdwScanPrivateRetrievedAttrs);
festate->conn = conn;
festate->query_executed = false;
festate->has_var_size_col = false;
festate->attinmeta = TupleDescGetAttInMetadata(tupleDescriptor);
festate->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
"mysql_fdw temporary data",
ALLOCSET_DEFAULT_SIZES);
if (wait_timeout > 0)
{
/* Set the session timeout in seconds */
sprintf(timeout, "SET wait_timeout = %d", wait_timeout);
mysql_query(festate->conn, timeout);
}
if (interactive_timeout > 0)
{
/* Set the session timeout in seconds */
sprintf(timeout, "SET interactive_timeout = %d", interactive_timeout);
mysql_query(festate->conn, timeout);
}
snprintf(sql_mode, sizeof(sql_mode), "SET sql_mode = '%s'",
options->sql_mode);
if (mysql_query(festate->conn, sql_mode) != 0)
mysql_error_print(festate->conn);
/* Initialize the MySQL statement */
festate->stmt = mysql_stmt_init(festate->conn);
if (festate->stmt == NULL)
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("failed to initialize the mysql query: \n%s",
mysql_error(festate->conn))));
/* Prepare MySQL statement */
if (mysql_stmt_prepare(festate->stmt, festate->query,
strlen(festate->query)) != 0)
mysql_stmt_error_print(festate, "failed to prepare the MySQL query");
/* Prepare for output conversion of parameters used in remote query. */
numParams = list_length(fsplan->fdw_exprs);
festate->numParams = numParams;
if (numParams > 0)
prepare_query_params((PlanState *) node,
fsplan->fdw_exprs,
numParams,
&festate->param_flinfo,
&festate->param_exprs,
&festate->param_values,
&festate->param_types);
/* int column_count = mysql_num_fields(festate->meta); */
/* Set the statement as cursor type */
mysql_stmt_attr_set(festate->stmt, STMT_ATTR_CURSOR_TYPE, (void *) &type);
/* Set the pre-fetch rows */
mysql_stmt_attr_set(festate->stmt, STMT_ATTR_PREFETCH_ROWS,
(void *) &options->fetch_size);
festate->table = (mysql_table *) palloc0(sizeof(mysql_table));
festate->table->column = (mysql_column *) palloc0(sizeof(mysql_column) * tupleDescriptor->natts);
festate->table->mysql_bind = (MYSQL_BIND *) palloc0(sizeof(MYSQL_BIND) * tupleDescriptor->natts);
festate->table->mysql_res = mysql_stmt_result_metadata(festate->stmt);
if (NULL == festate->table->mysql_res)
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("failed to retrieve query result set metadata: \n%s",
mysql_error(festate->conn))));
festate->table->mysql_fields = mysql_fetch_fields(festate->table->mysql_res);
foreach(lc, festate->retrieved_attrs)
{
int attnum = lfirst_int(lc) - 1;
Oid pgtype = TupleDescAttr(tupleDescriptor, attnum)->atttypid;
int32 pgtypmod = TupleDescAttr(tupleDescriptor, attnum)->atttypmod;
if (TupleDescAttr(tupleDescriptor, attnum)->attisdropped)
continue;
if (pgtype == TEXTOID)
festate->has_var_size_col = true;
festate->table->column[atindex].mysql_bind = &festate->table->mysql_bind[atindex];
mysql_bind_result(pgtype, pgtypmod,
&festate->table->mysql_fields[atindex],
&festate->table->column[atindex]);
atindex++;
}
/*
* Set STMT_ATTR_UPDATE_MAX_LENGTH so that mysql_stmt_store_result() can
* update metadata MYSQL_FIELD->max_length value, this will be useful to
* determine var length column size.
*/
mysql_stmt_attr_set(festate->stmt, STMT_ATTR_UPDATE_MAX_LENGTH,
&festate->has_var_size_col);
/* Bind the results pointers for the prepare statements */
if (mysql_stmt_bind_result(festate->stmt, festate->table->mysql_bind) != 0)
mysql_stmt_error_print(festate, "failed to bind the MySQL query");
}
/*
* mysqlIterateForeignScan
* Iterate and get the rows one by one from MySQL and placed in tuple
* slot
*/
static TupleTableSlot *
mysqlIterateForeignScan(ForeignScanState *node)
{
MySQLFdwExecState *festate = (MySQLFdwExecState *) node->fdw_state;
TupleTableSlot *tupleSlot = node->ss.ss_ScanTupleSlot;
int attid;
ListCell *lc;
int rc = 0;
Datum *dvalues;
bool *nulls;
int natts;
AttInMetadata *attinmeta = festate->attinmeta;
HeapTuple tup;
int i;
ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
List *fdw_private = fsplan->fdw_private;
natts = attinmeta->tupdesc->natts;
dvalues = palloc0(natts * sizeof(Datum));
nulls = palloc(natts * sizeof(bool));
/* Initialize to nulls for any columns not present in result */
memset(nulls, true, natts * sizeof(bool));
ExecClearTuple(tupleSlot);
/*
* If this is the first call after Begin or ReScan, we need to bind the
* params and execute the query.
*/
if (!festate->query_executed)
bind_stmt_params_and_exec(node);
attid = 0;
rc = mysql_stmt_fetch(festate->stmt);
if (rc == 0)
{
foreach(lc, festate->retrieved_attrs)
{
int attnum = lfirst_int(lc) - 1;
Oid pgtype = TupleDescAttr(attinmeta->tupdesc, attnum)->atttypid;
int32 pgtypmod = TupleDescAttr(attinmeta->tupdesc, attnum)->atttypmod;
nulls[attnum] = festate->table->column[attid].is_null;
if (!festate->table->column[attid].is_null)
dvalues[attnum] = mysql_convert_to_pg(pgtype, pgtypmod,
&festate->table->column[attid]);
attid++;
}
ExecClearTuple(tupleSlot);
if (list_length(fdw_private) >= mysqlFdwPrivateScanTList)
{
/* Construct tuple with whole-row references. */
tup = mysql_get_tuple_with_whole_row(festate, dvalues, nulls);
}
else
{
/* Form the Tuple using Datums */
tup = heap_form_tuple(attinmeta->tupdesc, dvalues, nulls);
}
if (tup)
ExecStoreHeapTuple(tup, tupleSlot, false);
else
mysql_stmt_close(festate->stmt);
/*
* Release locally palloc'd space and values of pass-by-reference
* datums, as well.
*/
for (i = 0; i < natts; i++)
{
if (dvalues[i] && !TupleDescAttr(attinmeta->tupdesc, i)->attbyval)
pfree(DatumGetPointer(dvalues[i]));
}
pfree(dvalues);
pfree(nulls);
}
else if (rc == 1)
{
/*
* Error occurred. Error code and message can be obtained by calling
* mysql_stmt_errno() and mysql_stmt_error().
*/
}
else if (rc == MYSQL_NO_DATA)
{
/*
* No more rows/data exists
*/
}
else if (rc == MYSQL_DATA_TRUNCATED)
{
/* Data truncation occurred */
/*
* MYSQL_DATA_TRUNCATED is returned when truncation reporting is
* enabled. To determine which column values were truncated when this
* value is returned, check the error members of the MYSQL_BIND
* structures used for fetching values. Truncation reporting is
* enabled by default, but can be controlled by calling
* mysql_options() with the MYSQL_REPORT_DATA_TRUNCATION option.
*/
}
return tupleSlot;
}
/*
* mysqlExplainForeignScan
* Produce extra output for EXPLAIN
*/
static void
mysqlExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
MySQLFdwExecState *festate = (MySQLFdwExecState *) node->fdw_state;
RangeTblEntry *rte;
ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
int rtindex;
EState *estate = node->ss.ps.state;
List *fdw_private = fsplan->fdw_private;
if (fsplan->scan.scanrelid > 0)
rtindex = fsplan->scan.scanrelid;
else
#if PG_VERSION_NUM >= 160000
rtindex = bms_next_member(fsplan->fs_base_relids, -1);
#else
rtindex = bms_next_member(fsplan->fs_relids, -1);
#endif
rte = rt_fetch(rtindex, estate->es_range_table);
if (list_length(fdw_private) > mysqlFdwScanPrivateRelations)
{
char *relations = strVal(list_nth(fdw_private,
mysqlFdwScanPrivateRelations));
ExplainPropertyText("Relations", relations, es);
}
/* Give some possibly useful info about startup costs */
if (es->costs)
{
mysql_opt *options = mysql_get_options(rte->relid, true);
if (strcmp(options->svr_address, "127.0.0.1") == 0 ||
strcmp(options->svr_address, "localhost") == 0)
ExplainPropertyInteger("Local server startup cost", NULL, 10, es);
else
ExplainPropertyInteger("Remote server startup cost", NULL, 25, es);
}
/* Show the remote query in verbose mode */
if (es->verbose)
ExplainPropertyText("Remote query", festate->query, es);
}
/*
* mysqlEndForeignScan
* Finish scanning foreign table and dispose objects used for this scan
*/
static void
mysqlEndForeignScan(ForeignScanState *node)
{
MySQLFdwExecState *festate = (MySQLFdwExecState *) node->fdw_state;
if (festate->table && festate->table->mysql_res)
{
mysql_free_result(festate->table->mysql_res);
festate->table->mysql_res = NULL;
}
if (festate->stmt)
{
mysql_stmt_close(festate->stmt);
festate->stmt = NULL;
}
}
/*
* mysqlReScanForeignScan
* Rescan table, possibly with new parameters
*/
static void
mysqlReScanForeignScan(ForeignScanState *node)
{
MySQLFdwExecState *festate = (MySQLFdwExecState *) node->fdw_state;
/*
* Set the query_executed flag to false so that the query will be executed
* in mysqlIterateForeignScan().
*/
festate->query_executed = false;
}
/*
* mysqlGetForeignRelSize
* Create a FdwPlan for a scan on the foreign table
*/
static void
mysqlGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel,
Oid foreigntableid)
{
double rows = 0;
double filtered = 0;
MYSQL *conn;
MYSQL_ROW row;