forked from EnterpriseDB/mysql_fdw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql_fdw.c
2168 lines (1893 loc) · 63.6 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-2014, EnterpriseDB Corporation.
*
* IDENTIFICATION
* mysql_fdw.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "mysql_fdw.h"
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dlfcn.h>
#include <mysql.h>
#include <errmsg.h>
#include "access/reloptions.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_user_mapping.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "commands/vacuum.h"
#include "foreign/fdwapi.h"
#include "foreign/foreign.h"
#include "nodes/makefuncs.h"
#include "optimizer/cost.h"
#include "optimizer/pathnode.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "storage/ipc.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/date.h"
#include "utils/hsearch.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/timestamp.h"
#include "utils/formatting.h"
#include "utils/memutils.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "commands/vacuum.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/cost.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/planmain.h"
#include "optimizer/prep.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/var.h"
#include "parser/parsetree.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "optimizer/pathnode.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/planmain.h"
#include "mysql_query.h"
#define DEFAULTE_NUM_ROWS 1000
PG_MODULE_MAGIC;
typedef struct MySQLFdwRelationInfo
{
/* baserestrictinfo clauses, broken down into safe and unsafe subsets. */
List *remote_conds;
List *local_conds;
/* Bitmap of attr numbers we need to fetch from the remote server. */
Bitmapset *attrs_used;
} MySQLFdwRelationInfo;
extern Datum mysql_fdw_handler(PG_FUNCTION_ARGS);
extern PGDLLEXPORT void _PG_init(void);
bool mysql_load_library(void);
static void mysql_fdw_exit(int code, Datum arg);
PG_FUNCTION_INFO_V1(mysql_fdw_handler);
/*
* 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);
static void mysqlAddForeignUpdateTargets(Query *parsetree, RangeTblEntry *target_rte,
Relation target_relation);
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 *baserel, Oid foreigntableid,
ForeignPath *best_path, List * tlist, List *scan_clauses
#if PG_VERSION_NUM >= 90500
,Plan * outer_plan
#endif
);
static void mysqlEstimateCosts(PlannerInfo *root, RelOptInfo *baserel, Cost *startup_cost, Cost *total_cost,
Oid foreigntableid);
#if PG_VERSION_NUM >= 90500
static List *mysqlImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid);
#endif
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 create_cursor(ForeignScanState *node);
void* mysql_dll_handle = NULL;
static int wait_timeout = WAIT_TIMEOUT;
static int interactive_timeout = INTERACTIVE_TIMEOUT;
/*
* 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__)
/*
* 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);
/* Callback functions for readable FDW */
fdwroutine->GetForeignRelSize = mysqlGetForeignRelSize;
fdwroutine->GetForeignPaths = mysqlGetForeignPaths;
fdwroutine->AnalyzeForeignTable = mysqlAnalyzeForeignTable;
fdwroutine->GetForeignPlan = mysqlGetForeignPlan;
fdwroutine->ExplainForeignScan = mysqlExplainForeignScan;
fdwroutine->BeginForeignScan = mysqlBeginForeignScan;
fdwroutine->IterateForeignScan = mysqlIterateForeignScan;
fdwroutine->ReScanForeignScan = mysqlReScanForeignScan;
fdwroutine->EndForeignScan = mysqlEndForeignScan;
#if PG_VERSION_NUM >= 90500
fdwroutine->ImportForeignSchema = mysqlImportForeignSchema;
#endif
/* Callback functions for writeable FDW */
fdwroutine->ExecForeignInsert = mysqlExecForeignInsert;
fdwroutine->BeginForeignModify = mysqlBeginForeignModify;
fdwroutine->PlanForeignModify = mysqlPlanForeignModify;
fdwroutine->AddForeignUpdateTargets = mysqlAddForeignUpdateTargets;
fdwroutine->ExecForeignUpdate = mysqlExecForeignUpdate;
fdwroutine->ExecForeignDelete = mysqlExecForeignDelete;
fdwroutine->EndForeignModify = mysqlEndForeignModify;
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 = NULL;
RangeTblEntry *rte;
MySQLFdwExecState *festate = NULL;
EState *estate = node->ss.ps.state;
ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
mysql_opt *options;
ListCell *lc = NULL;
int atindex = 0;
unsigned long prefetch_rows = MYSQL_PREFETCH_ROWS;
unsigned long type = (unsigned long) CURSOR_TYPE_READ_ONLY;
Oid userid;
ForeignServer *server;
UserMapping *user;
ForeignTable *table;
char timeout[255];
int numParams;
/*
* We'll save private state in node->fdw_state.
*/
festate = (MySQLFdwExecState *) palloc(sizeof(MySQLFdwExecState));
node->fdw_state = (void *) festate;
/*
* Identify which user to do the remote access as. This should match what
* ExecCheckRTEPerms() does.
*/
rte = rt_fetch(fsplan->scan.scanrelid, estate->es_range_table);
userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
/* Get info about foreign table. */
festate->rel = node->ss.ss_currentRelation;
table = GetForeignTable(RelationGetRelid(festate->rel));
server = GetForeignServer(table->serverid);
user = GetUserMapping(userid, server->serverid);
/* Fetch the options */
options = mysql_get_options(RelationGetRelid(node->ss.ss_currentRelation));
/*
* 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, 0));
festate->retrieved_attrs = list_nth(fsplan->fdw_private, 1);
festate->conn = conn;
festate->cursor_exists = false;
festate->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
"mysql_fdw temporary data",
ALLOCSET_SMALL_MINSIZE,
ALLOCSET_SMALL_INITSIZE,
ALLOCSET_SMALL_MAXSIZE);
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);
}
_mysql_query(festate->conn, "SET time_zone = '+00:00'");
_mysql_query(festate->conn, "SET sql_mode='ANSI_QUOTES'");
/* Initialize the MySQL statement */
festate->stmt = _mysql_stmt_init(festate->conn);
if (festate->stmt == NULL)
{
char *err = pstrdup(_mysql_error(festate->conn));
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("failed to initialize the mysql query: \n%s", err)));
}
/* Prepare MySQL statement */
if (_mysql_stmt_prepare(festate->stmt, festate->query, strlen(festate->query)) != 0)
{
switch(_mysql_stmt_errno(festate->stmt))
{
case CR_NO_ERROR:
break;
case CR_OUT_OF_MEMORY:
case CR_SERVER_GONE_ERROR:
case CR_SERVER_LOST:
{
char *err = pstrdup(_mysql_error(festate->conn));
mysql_rel_connection(festate->conn);
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("failed to prepare the MySQL query: \n%s", err)));
}
break;
case CR_COMMANDS_OUT_OF_SYNC:
case CR_UNKNOWN_ERROR:
default:
{
char *err = pstrdup(_mysql_error(festate->conn));
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("failed to prepare the MySQL query: \n%s", err)));
}
break;
}
}
/* 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);
/*
* If this is the first call after Begin or ReScan, we need to create the
* cursor on the remote side.
*/
if (!festate->cursor_exists)
create_cursor(node);
/* 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*) &prefetch_rows);
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)
{
char *err = pstrdup(_mysql_error(festate->conn));
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("failed to retrieve query result set metadata: \n%s", err)));
}
festate->table->_mysql_fields = _mysql_fetch_fields(festate->table->_mysql_res);
foreach(lc, festate->retrieved_attrs)
{
int attnum = lfirst_int(lc) - 1;
Oid pgtype = tupleDescriptor->attrs[attnum]->atttypid;
int32 pgtypmod = tupleDescriptor->attrs[attnum]->atttypmod;
if (tupleDescriptor->attrs[attnum]->attisdropped)
continue;
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++;
}
/* Bind the results pointers for the prepare statements */
if (_mysql_stmt_bind_result(festate->stmt, festate->table->_mysql_bind) != 0)
{
switch(_mysql_stmt_errno(festate->stmt))
{
case CR_NO_ERROR:
break;
case CR_OUT_OF_MEMORY:
case CR_SERVER_GONE_ERROR:
case CR_SERVER_LOST:
{
char *err = pstrdup(_mysql_error(festate->conn));
mysql_rel_connection(festate->conn);
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("failed to bind the MySQL query: \n%s", err)));
}
break;
case CR_COMMANDS_OUT_OF_SYNC:
case CR_UNKNOWN_ERROR:
default:
{
char *err = pstrdup(_mysql_error(festate->conn));
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("failed to bind the MySQL query: \n%s", err)));
}
break;
}
}
/*
* Finally execute the query and result will be placed in the
* array we already bind
*/
if (_mysql_stmt_execute(festate->stmt) != 0)
{
switch(_mysql_stmt_errno(festate->stmt))
{
case CR_NO_ERROR:
break;
case CR_OUT_OF_MEMORY:
case CR_SERVER_GONE_ERROR:
case CR_SERVER_LOST:
{
char *err = pstrdup(_mysql_error(festate->conn));
mysql_rel_connection(festate->conn);
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg(" 7 failed to execute the MySQL query: \n%s", err)));
}
break;
case CR_COMMANDS_OUT_OF_SYNC:
case CR_UNKNOWN_ERROR:
default:
{
char *err = pstrdup(_mysql_error(festate->conn));
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("failed to execute the MySQL query: \n%s", err)));
}
break;
}
}
}
/*
* 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;
TupleDesc tupleDescriptor = tupleSlot->tts_tupleDescriptor;
int attid = 0;
ListCell *lc = NULL;
int rc = 0;
memset (tupleSlot->tts_values, 0, sizeof(Datum) * tupleDescriptor->natts);
memset (tupleSlot->tts_isnull, true, sizeof(bool) * tupleDescriptor->natts);
ExecClearTuple(tupleSlot);
attid = 0;
rc = _mysql_stmt_fetch(festate->stmt);
if (0 == rc)
{
foreach(lc, festate->retrieved_attrs)
{
int attnum = lfirst_int(lc) - 1;
Oid pgtype = tupleDescriptor->attrs[attnum]->atttypid;
int32 pgtypmod = tupleDescriptor->attrs[attnum]->atttypmod;
tupleSlot->tts_isnull[attnum] = festate->table->column[attid].is_null;
if (!festate->table->column[attid].is_null)
tupleSlot->tts_values[attnum] = mysql_convert_to_pg(pgtype, pgtypmod,
&festate->table->column[attid]);
attid++;
}
ExecStoreVirtualTuple(tupleSlot);
}
else if (1 == rc)
{
/*
Error occurred. Error code and message can be obtained
by calling mysql_stmt_errno() and mysql_stmt_error().
*/
}
else if (MYSQL_NO_DATA == rc)
{
/*
No more rows/data exists
*/
}
else if (MYSQL_DATA_TRUNCATED == rc)
{
/* 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;
mysql_opt *options;
/* Fetch options */
options = mysql_get_options(RelationGetRelid(node->ss.ss_currentRelation));
/* Give some possibly useful info about startup costs */
if (es->verbose)
{
if (strcmp(options->svr_address, "127.0.0.1") == 0 || strcmp(options->svr_address, "localhost") == 0)
ExplainPropertyLong("Local server startup cost", 10, es);
else
ExplainPropertyLong("Remote server startup cost", 25, es);
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)
{
if (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)
{
/* TODO: Need to implement rescan */
}
/*
* mysqlGetForeignRelSize: Create a FdwPlan for a scan on the foreign table
*/
static void
mysqlGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
{
StringInfoData sql;
double rows = 0;
double filtered = 0;
MYSQL *conn = NULL;
MYSQL_RES *result = NULL;
MYSQL_ROW row;
Bitmapset *attrs_used = NULL;
List *retrieved_attrs = NULL;
mysql_opt *options = NULL;
Oid userid = GetUserId();
ForeignServer *server;
UserMapping *user;
ForeignTable *table;
MySQLFdwRelationInfo *fpinfo;
ListCell *lc;
MYSQL_FIELD *field;
int i;
int num_fields;
List *params_list = NULL;
fpinfo = (MySQLFdwRelationInfo *) palloc0(sizeof(MySQLFdwRelationInfo));
baserel->fdw_private = (void *) fpinfo;
table = GetForeignTable(foreigntableid);
server = GetForeignServer(table->serverid);
user = GetUserMapping(userid, server->serverid);
/* Fetch options */
options = mysql_get_options(foreigntableid);
/* Connect to the server */
conn = mysql_get_connection(server, user, options);
_mysql_query(conn, "SET sql_mode='ANSI_QUOTES'");
#if PG_VERSION_NUM >= 90600
pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid, &attrs_used);
#else
pull_varattnos((Node *) baserel->reltargetlist, baserel->relid, &attrs_used);
#endif
foreach(lc, baserel->baserestrictinfo)
{
RestrictInfo *ri = (RestrictInfo *) lfirst(lc);
if (is_foreign_expr(root, baserel, ri->clause))
fpinfo->remote_conds = lappend(fpinfo->remote_conds, ri);
else
fpinfo->local_conds = lappend(fpinfo->local_conds, ri);
}
#if PG_VERSION_NUM >= 90600
pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid, &fpinfo->attrs_used);
#else
pull_varattnos((Node *) baserel->reltargetlist, baserel->relid, &fpinfo->attrs_used);
#endif
foreach(lc, fpinfo->local_conds)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
pull_varattnos((Node *) rinfo->clause, baserel->relid, &fpinfo->attrs_used);
}
if (options->use_remote_estimate)
{
initStringInfo(&sql);
appendStringInfo(&sql, "EXPLAIN ");
mysql_deparse_select(&sql, root, baserel, fpinfo->attrs_used, options->svr_table, &retrieved_attrs);
if (fpinfo->remote_conds)
mysql_append_where_clause(&sql, root, baserel, fpinfo->remote_conds,
true, ¶ms_list);
if (_mysql_query(conn, sql.data) != 0)
{
switch(_mysql_errno(conn))
{
case CR_NO_ERROR:
break;
case CR_OUT_OF_MEMORY:
case CR_SERVER_GONE_ERROR:
case CR_SERVER_LOST:
case CR_UNKNOWN_ERROR:
{
char *err = pstrdup(_mysql_error(conn));
mysql_rel_connection(conn);
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("failed to execute the MySQL query: \n%s", err)));
}
break;
case CR_COMMANDS_OUT_OF_SYNC:
default:
{
char *err = pstrdup(_mysql_error(conn));
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("failed to execute the MySQL query: \n%s", err)));
}
}
}
result = _mysql_store_result(conn);
if (result)
{
/*
* MySQL provide numbers of rows per table invole in
* the statment, but we don't have problem with it
* because we are sending separate query per table
* in FDW.
*/
row = _mysql_fetch_row(result);
num_fields = _mysql_num_fields(result);
if (row)
{
for (i = 0; i < num_fields; i++)
{
field = _mysql_fetch_field(result);
if (strcmp(field->name, "rows") == 0)
{
if (row[i])
rows = atof(row[i]);
}
else if (strcmp(field->name, "filtered") == 0)
{
if (row[i])
filtered = atof(row[i]);
}
}
}
_mysql_free_result(result);
}
}
if (rows > 0)
rows = ((rows + 1) * filtered) / 100;
else
rows = DEFAULTE_NUM_ROWS;
baserel->rows = rows;
baserel->tuples = rows;
}
static bool
mysql_is_column_unique(Oid foreigntableid)
{
StringInfoData sql;
MYSQL *conn = NULL;
MYSQL_RES *result = NULL;
MYSQL_ROW row;
mysql_opt *options = NULL;
Oid userid = GetUserId();
ForeignServer *server;
UserMapping *user;
ForeignTable *table;
table = GetForeignTable(foreigntableid);
server = GetForeignServer(table->serverid);
user = GetUserMapping(userid, server->serverid);
/* Fetch the options */
options = mysql_get_options(foreigntableid);
/* Connect to the server */
conn = mysql_get_connection(server, user, options);
/* Build the query */
initStringInfo(&sql);
appendStringInfo(&sql, "EXPLAIN %s", options->svr_table);
if (_mysql_query(conn, sql.data) != 0)
{
switch(_mysql_errno(conn))
{
case CR_NO_ERROR:
break;
case CR_OUT_OF_MEMORY:
case CR_SERVER_GONE_ERROR:
case CR_SERVER_LOST:
case CR_UNKNOWN_ERROR:
{
char *err = pstrdup(_mysql_error(conn));
mysql_rel_connection(conn);
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("failed to execute the MySQL query: \n%s", err)));
}
break;
case CR_COMMANDS_OUT_OF_SYNC:
default:
{
char *err = pstrdup(_mysql_error(conn));
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("failed to execute the MySQL query: \n%s", err)));
}
}
}
result = _mysql_store_result(conn);
if (result)
{
int num_fields = _mysql_num_fields(result);
row = _mysql_fetch_row(result);
if (row && num_fields > 3)
{
if ((strcmp(row[3], "PRI") == 0) || (strcmp(row[3], "UNI")) == 0)
{
_mysql_free_result(result);
return true;
}
}
_mysql_free_result(result);
}
return false;
}
/*
* mysqlEstimateCosts: Estimate the remote query cost
*/
static void
mysqlEstimateCosts(PlannerInfo *root, RelOptInfo *baserel, Cost *startup_cost, Cost *total_cost, Oid foreigntableid)
{
mysql_opt *options;
/* Fetch options */
options = mysql_get_options(foreigntableid);
/* Local databases are probably faster */
if (strcmp(options->svr_address, "127.0.0.1") == 0 || strcmp(options->svr_address, "localhost") == 0)
*startup_cost = 10;
else
*startup_cost = 25;
*total_cost = baserel->rows + *startup_cost;
}
/*
* mysqlGetForeignPaths: Get the foreign paths
*/
static void
mysqlGetForeignPaths(PlannerInfo *root,RelOptInfo *baserel,Oid foreigntableid)
{
Cost startup_cost;
Cost total_cost;
/* Estimate costs */
mysqlEstimateCosts(root, baserel, &startup_cost, &total_cost, foreigntableid);
/* Create a ForeignPath node and add it as only possible path */
add_path(baserel, (Path *)
create_foreignscan_path(root, baserel,
#if PG_VERSION_NUM >= 90600
NULL, /* default pathtarget */
#endif
baserel->rows,