forked from EnterpriseDB/mysql_fdw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql_fdw.c
1578 lines (1379 loc) · 45.4 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"
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);
static void mysqlEstimateCosts(PlannerInfo *root, RelOptInfo *baserel, Cost *startup_cost, Cost *total_cost,
Oid foreigntableid);
static bool mysql_is_column_unique(Oid foreigntableid);
#ifdef __APPLE__
#define _MYSQL_LIBNAME "libmysqlclient.dylib"
#else
#define _MYSQL_LIBNAME "libmysqlclient.so"
#endif
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__) || 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_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_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");
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_stmt_close == NULL ||
_mysql_stmt_reset == NULL ||
_mysql_free_result == NULL ||
_mysql_error == NULL ||
_mysql_options == 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)
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;
/* Callback functions for readable 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;
MYSQL_BIND *mysql_result_buffer = 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];
/*
* 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->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
"mysql_fdw temporary data",
ALLOCSET_SMALL_MINSIZE,
ALLOCSET_SMALL_INITSIZE,
ALLOCSET_SMALL_MAXSIZE);
/* Allocate memory for the values and nulls for the results */
festate->tts_values = (Datum*) palloc0(sizeof(Datum) * tupleDescriptor->natts);
festate->tts_isnull = palloc0(sizeof(bool) * tupleDescriptor->natts);
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;
}
}
/* 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);
mysql_result_buffer = (MYSQL_BIND*) palloc0(sizeof(MYSQL_BIND) * tupleDescriptor->natts);
foreach(lc, festate->retrieved_attrs)
{
int attnum = lfirst_int(lc) - 1;
if (tupleDescriptor->attrs[attnum]->attisdropped)
continue;
festate->tts_values[atindex] = mysql_bind_result(atindex, &festate->tts_values[atindex],
(bool*)&festate->tts_isnull[atindex], mysql_result_buffer);
atindex++;
}
/* Bind the results pointers for the prepare statements */
if (_mysql_stmt_bind_result(festate->stmt, mysql_result_buffer) != 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;
memset (tupleSlot->tts_values, 0, sizeof(Datum) * tupleDescriptor->natts);
memset (tupleSlot->tts_isnull, true, sizeof(bool) * tupleDescriptor->natts);
ExecClearTuple(tupleSlot);
attid = 0;
if (_mysql_stmt_fetch(festate->stmt) == 0)
{
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->tts_isnull[attid];
if (!festate->tts_isnull[attid])
tupleSlot->tts_values[attnum] = mysql_convert_to_pg(pgtype, pgtypmod,
festate->tts_values[attid], festate);
attid++;
}
ExecStoreVirtualTuple(tupleSlot);
}
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->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;
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;
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'");
/* Build the query */
initStringInfo(&sql);
pull_varattnos((Node *) baserel->reltargetlist, baserel->relid, &attrs_used);
appendStringInfo(&sql, "EXPLAIN ");
mysql_deparse_select(&sql, root, baserel, attrs_used, options->svr_table, &retrieved_attrs);
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);
}
pull_varattnos((Node *) baserel->reltargetlist, baserel->relid, &fpinfo->attrs_used);
foreach(lc, fpinfo->local_conds)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
pull_varattnos((Node *) rinfo->clause, baserel->relid, &fpinfo->attrs_used);
}
/*
* TODO: MySQL seems to have some pretty unhelpful EXPLAIN output, which only
* gives a row estimate for each relation in the statement. We'll use the
* sum of the rows as our cost estimate - it's not great (in fact, in some
* cases it sucks), but it's all we've got for now.
*/
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)
{
while ((row = _mysql_fetch_row(result)))
rows += row[8] ? atof(row[8]) : 2;
_mysql_free_result(result);
}
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,
baserel->rows,
startup_cost,
total_cost,
NULL, /* no pathkeys */
NULL, /* no outer rel either */
NULL)); /* no fdw_private data */
}
/*
* mysqlGetForeignPlan: Get a foreign scan plan node
*/
static ForeignScan *
mysqlGetForeignPlan(PlannerInfo *root,RelOptInfo *baserel, Oid foreigntableid, ForeignPath *best_path, List * tlist, List *scan_clauses)
{
MySQLFdwRelationInfo *fpinfo = (MySQLFdwRelationInfo *) baserel->fdw_private;
Index scan_relid = baserel->relid;
List *fdw_private;
List *local_exprs = NULL;
List *params_list = NULL;
List *remote_conds = NIL;
StringInfoData sql;
mysql_opt *options;
List *retrieved_attrs;
ListCell *lc;
/* Fetch options */
options = mysql_get_options(foreigntableid);
/*
* Build the query string to be sent for execution, and identify
* expressions to be sent as parameters.
*/
/* Build the query */
initStringInfo(&sql);
/*
* Separate the scan_clauses into those that can be executed remotely and
* those that can't. baserestrictinfo clauses that were previously
* determined to be safe or unsafe by classifyConditions are shown in
* fpinfo->remote_conds and fpinfo->local_conds. Anything else in the
* scan_clauses list will be a join clause, which we have to check for
* remote-safety.
*
* Note: the join clauses we see here should be the exact same ones
* previously examined by postgresGetForeignPaths. Possibly it'd be worth
* passing forward the classification work done then, rather than
* repeating it here.
*
* This code must match "extract_actual_clauses(scan_clauses, false)"
* except for the additional decision about remote versus local execution.
* Note however that we only strip the RestrictInfo nodes from the
* local_exprs list, since appendWhereClause expects a list of
* RestrictInfos.
*/
foreach(lc, scan_clauses)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
Assert(IsA(rinfo, RestrictInfo));
/* Ignore any pseudoconstants, they're dealt with elsewhere */
if (rinfo->pseudoconstant)
continue;
if (list_member_ptr(fpinfo->remote_conds, rinfo))
remote_conds = lappend(remote_conds, rinfo);
else if (list_member_ptr(fpinfo->local_conds, rinfo))
local_exprs = lappend(local_exprs, rinfo->clause);
else if (is_foreign_expr(root, baserel, rinfo->clause))
remote_conds = lappend(remote_conds, rinfo);
else
local_exprs = lappend(local_exprs, rinfo->clause);
}
mysql_deparse_select(&sql, root, baserel, fpinfo->attrs_used, options->svr_table, &retrieved_attrs);
if (remote_conds)
mysql_append_where_clause(&sql, root, baserel, remote_conds,
true, ¶ms_list);
if (baserel->relid == root->parse->resultRelation &&
(root->parse->commandType == CMD_UPDATE ||
root->parse->commandType == CMD_DELETE))
{
/* Relation is UPDATE/DELETE target, so use FOR UPDATE */
appendStringInfoString(&sql, " FOR UPDATE");
}
/*
* Build the fdw_private list that will be available to the executor.
* Items in the list must match enum FdwScanPrivateIndex, above.
*/
fdw_private = list_make2(makeString(sql.data), retrieved_attrs);
/*
* Create the ForeignScan node from target list, local filtering
* expressions, remote parameter expressions, and FDW private information.
*
* Note that the remote parameter expressions are stored in the fdw_exprs
* field of the finished plan node; we can't keep them in private state
* because then they wouldn't be subject to later planner processing.
*/
return make_foreignscan(tlist,
local_exprs,
scan_relid,
params_list,
fdw_private);
}
/*
* mysqlAnalyzeForeignTable: Implement stats collection
*/
static bool
mysqlAnalyzeForeignTable(Relation relation, AcquireSampleRowsFunc *func, BlockNumber *totalpages)
{
StringInfoData sql;
double table_size = 0;
MYSQL *conn;
MYSQL_RES *result;
MYSQL_ROW row;
Oid foreignTableId = RelationGetRelid(relation);
mysql_opt *options;
char *relname;
ForeignServer *server;
UserMapping *user;
ForeignTable *table;
table = GetForeignTable(foreignTableId);
server = GetForeignServer(table->serverid);
user = GetUserMapping(relation->rd_rel->relowner, server->serverid);
/* Fetch options */
options = mysql_get_options(foreignTableId);
/* Connect to the server */
conn = mysql_get_connection(server, user, options);
/* Build the query */
initStringInfo(&sql);
/* If no table name specified, use the foreign table name */
relname = options->svr_table;
if ( relname == NULL)
relname = RelationGetRelationName(relation);
mysql_deparse_analyze(&sql, options->svr_database, relname);
if (_mysql_query(conn, sql.data) != 0)
{
switch(_mysql_errno(conn))
{
case CR_NO_ERROR: