forked from pgspider/jdbc_fdw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jdbc_fdw.c
3135 lines (2755 loc) · 90.1 KB
/
jdbc_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
/*-------------------------------------------------------------------------
*
* jdbc_fdw.c
* Foreign-data wrapper for remote PostgreSQL servers
*
* Portions Copyright (c) 2012-2014, PostgreSQL Global Development Group
*
* Portions Copyright (c) 2021, TOSHIBA CORPORATION
*
* IDENTIFICATION
* contrib/jdbc_fdw/jdbc_fdw.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "jdbc_fdw.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/appendinfo.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/planmain.h"
#include "optimizer/planner.h"
#include "optimizer/prep.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/tlist.h"
#include "parser/parsetree.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/elog.h"
#include "executor/spi.h"
#include "storage/ipc.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_user_mapping.h"
#define Str(arg) #arg
#define StrValue(arg) Str(arg)
#define STR_PKGLIBDIR StrValue(PKG_LIB_DIR)
#define IS_KEY_COLUMN(A) ((strcmp(A->defname, "key") == 0) && \
(strcmp(strVal(A->arg), "true") == 0))
PG_MODULE_MAGIC;
/* Default CPU cost to start up a foreign query. */
#define DEFAULT_FDW_STARTUP_COST 100.0
/* Default CPU cost to process 1 row (above and beyond cpu_tuple_cost). */
#define DEFAULT_FDW_TUPLE_COST 0.01
/*
* Indexes of FDW-private information stored in fdw_private lists.
*
* We store various information in ForeignScan.fdw_private to pass it from
* planner to executor. Currently we store:
*
* 1) SELECT statement text to be sent to the remote server 2) Integer list
* of attribute numbers retrieved by the SELECT
*
* These items are indexed with the enum FdwScanPrivateIndex, so an item can
* be fetched with list_nth(). For example, to get the SELECT statement: sql
* = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
*/
enum FdwScanPrivateIndex
{
/* SQL statement to execute remotely (as a String node) */
FdwScanPrivateSelectSql,
/* Integer list of attribute numbers retrieved by the SELECT */
FdwScanPrivateRetrievedAttrs
};
/*
* 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 a Boolean node) */
FdwPathPrivateHasFinalSort,
/* has-limit flag (as a Boolean node) */
FdwPathPrivateHasLimit
};
/*
* Similarly, this enum describes what's kept in the fdw_private list for a
* ModifyTable node referencing a jdbc_fdw foreign table. We store:
*
* 1) INSERT/UPDATE/DELETE statement text to be sent to the remote server 2)
* Integer list of target attribute numbers for INSERT/UPDATE (NIL for a
* DELETE) 3) Boolean flag showing if the remote query has a RETURNING clause
* 4) Integer list of attribute numbers retrieved by RETURNING, if any
*/
enum FdwModifyPrivateIndex
{
/* SQL statement to execute remotely (as a String node) */
FdwModifyPrivateUpdateSql,
/* Integer list of target attribute numbers for INSERT/UPDATE */
FdwModifyPrivateTargetAttnums,
/* has-returning flag (as a Boolean node) */
FdwModifyPrivateHasReturning,
/* Integer list of attribute numbers retrieved by RETURNING */
FdwModifyPrivateRetrievedAttrs
};
/*
* Execution state of a foreign scan using jdbc_fdw.
*/
typedef struct jdbcFdwScanState
{
Relation rel; /* relcache entry for the foreign table */
AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
TupleDesc tupdesc; /* tuple descriptor of scan */
/* extracted fdw_private data */
char *query; /* text of SELECT command */
List *retrieved_attrs; /* list of retrieved attribute numbers */
/* for remote query execution */
Jconn *conn; /* connection for the scan */
unsigned int cursor_number; /* quasi-unique ID for my cursor */
bool cursor_exists; /* have we created the cursor? */
int numParams; /* number of parameters passed to query */
FmgrInfo *param_flinfo; /* output conversion functions for them */
List *param_exprs; /* executable expressions for param values */
const char **param_values; /* textual values of query parameters */
/* for storing result tuples */
HeapTuple *tuples; /* array of currently-retrieved tuples */
int num_tuples; /* # of tuples in array */
int next_tuple; /* index of next one to return */
/*
* batch-level state, for optimizing rewinds and avoiding useless fetch
*/
int fetch_ct_2; /* Min(# of fetches done, 2) */
bool eof_reached; /* true if last fetch reached EOF */
/* working memory contexts */
MemoryContext batch_cxt; /* context holding current batch of tuples */
MemoryContext temp_cxt; /* context for per-tuple temporary data */
/* for the execution of the result from java side */
int resultSetID;
} jdbcFdwScanState;
/*
* Execution state of a foreign insert/update/delete operation.
*/
typedef struct jdbcFdwModifyState
{
Relation rel; /* relcache entry for the foreign table */
AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
/* for remote query execution */
Jconn *conn; /* connection for the scan */
bool is_prepared; /* name of prepared statement, if created */
/* extracted fdw_private data */
char *query; /* text of INSERT/UPDATE/DELETE command */
List *target_attrs; /* list of target attribute numbers */
bool has_returning; /* is there a RETURNING clause? */
List *retrieved_attrs; /* attr numbers retrieved by RETURNING */
/* info about parameters for prepared statement */
AttrNumber *junk_idx; /* the attrnumber of the junk column for
* UPDATE and DELETE */
int p_nums; /* number of parameters to transmit */
FmgrInfo *p_flinfo; /* output conversion functions for them */
/* working memory context */
MemoryContext temp_cxt; /* context for per-tuple temporary data */
/* for the execution of the result from java side */
int resultSetID;
} jdbcFdwModifyState;
/*
* Workspace for analyzing a foreign table.
*/
typedef struct jdbcFdwAnalyzeState
{
Relation rel; /* relcache entry for the foreign table */
AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
List *retrieved_attrs; /* attr numbers retrieved by query */
/* collected sample rows */
HeapTuple *rows; /* array of size targrows */
int targrows; /* target # of sample rows */
int numrows; /* # of sample rows collected */
/* for random sampling */
double samplerows; /* # of rows fetched */
double rowstoskip; /* # of rows to skip before next sample */
double rstate; /* random state */
/* working memory contexts */
MemoryContext anl_cxt; /* context for per-analyze lifespan data */
MemoryContext temp_cxt; /* context for per-tuple temporary data */
} jdbcFdwAnalyzeState;
/*
* Identify the attribute where data conversion fails.
*/
typedef struct ConversionLocation
{
Relation rel; /* foreign table's relcache entry */
AttrNumber cur_attno; /* attribute number being processed, or 0 */
} ConversionLocation;
/*
* SQL functions
*/
PG_FUNCTION_INFO_V1(jdbc_fdw_handler);
PG_FUNCTION_INFO_V1(jdbc_fdw_version);
PG_FUNCTION_INFO_V1(jdbc_exec);
/*
* FDW callback routines
*/
static void jdbcGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
static void jdbcGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
static ForeignScan *jdbcGetForeignPlan(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses,
Plan *outer_plan
);
static void jdbcBeginForeignScan(ForeignScanState *node, int eflags);
static TupleTableSlot *jdbcIterateForeignScan(ForeignScanState *node);
static void jdbcReScanForeignScan(ForeignScanState *node);
static void jdbcEndForeignScan(ForeignScanState *node);
static void jdbcAddForeignUpdateTargets(
#if PG_VERSION_NUM >= 140000
PlannerInfo *root,
Index rtindex,
#else
Query *parsetree,
#endif
RangeTblEntry *target_rte,
Relation target_relation);
static List *jdbcPlanForeignModify(PlannerInfo *root,
ModifyTable *plan,
Index resultRelation,
int subplan_index);
static void jdbcBeginForeignModify(ModifyTableState *mtstate,
ResultRelInfo *resultRelInfo,
List *fdw_private,
int subplan_index,
int eflags);
static TupleTableSlot *jdbcExecForeignInsert(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static TupleTableSlot *jdbcExecForeignUpdate(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static TupleTableSlot *jdbcExecForeignDelete(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static void jdbcEndForeignModify(EState *estate,
ResultRelInfo *resultRelInfo);
static int jdbcIsForeignRelUpdatable(Relation rel);
static void jdbcExplainForeignScan(ForeignScanState *node,
ExplainState *es);
static void jdbcExplainForeignModify(ModifyTableState *mtstate,
ResultRelInfo *rinfo,
List *fdw_private,
int subplan_index,
ExplainState *es);
static bool jdbcAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
static List *jdbcImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
static void jdbcGetForeignUpperPaths(PlannerInfo *root,
UpperRelationKind stage,
RelOptInfo *input_rel,
RelOptInfo *output_rel
#if (PG_VERSION_NUM >= 110000)
,void *extra
#endif
);
/*
* Helper functions
*/
static void estimate_path_cost_size(PlannerInfo *root,
RelOptInfo *baserel,
List *join_conds,
double *p_rows, int *p_width,
Cost *p_startup_cost,
Cost *p_total_cost,
char *q_char);
static void get_remote_estimate(const char *sql,
Jconn * conn,
double *rows,
int *width,
Cost *startup_cost,
Cost *total_cost);
static void jdbc_close_cursor(Jconn * conn, unsigned int cursor_number);
static void jdbc_prepare_foreign_modify(jdbcFdwModifyState * fmstate);
static bool jdbc_foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel);
static void jdbc_add_foreign_grouping_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *grouped_rel
#if (PG_VERSION_NUM >= 110000)
,GroupPathExtraData *extra
#endif
);
static void jdbc_add_foreign_final_paths(PlannerInfo *root, RelOptInfo *input_rel,
RelOptInfo *final_rel
#if (PG_VERSION_NUM >= 120000)
,FinalPathExtraData *extra
#endif
);
static void jdbc_execute_commands(List *cmd_list);
static void jdbc_bind_junk_column_value(jdbcFdwModifyState * fmstate,
TupleTableSlot *slot,
TupleTableSlot *planSlot,
Oid foreignTableId,
int bindnum);
static void prepTuplestoreResult(FunctionCallInfo fcinfo);
static Jconn *jdbc_get_conn_by_server_name(char *servername);
static TupleDesc jdbc_create_descriptor(Jconn *conn, int *resultSetID);
static Oid jdbc_convert_type_name(char *typname);
/*
* Foreign-data wrapper handler function: return a struct with pointers to my
* callback routines.
*/
Datum
jdbc_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *routine = makeNode(FdwRoutine);
/* Functions for scanning foreign tables */
routine->GetForeignRelSize = jdbcGetForeignRelSize;
routine->GetForeignPaths = jdbcGetForeignPaths;
routine->GetForeignPlan = jdbcGetForeignPlan;
routine->BeginForeignScan = jdbcBeginForeignScan;
routine->IterateForeignScan = jdbcIterateForeignScan;
routine->ReScanForeignScan = jdbcReScanForeignScan;
routine->EndForeignScan = jdbcEndForeignScan;
/* Functions for updating foreign tables */
routine->AddForeignUpdateTargets = jdbcAddForeignUpdateTargets;
routine->PlanForeignModify = jdbcPlanForeignModify;
routine->BeginForeignModify = jdbcBeginForeignModify;
routine->ExecForeignInsert = jdbcExecForeignInsert;
routine->ExecForeignUpdate = jdbcExecForeignUpdate;
routine->ExecForeignDelete = jdbcExecForeignDelete;
routine->EndForeignModify = jdbcEndForeignModify;
routine->IsForeignRelUpdatable = jdbcIsForeignRelUpdatable;
/* Support functions for EXPLAIN */
routine->ExplainForeignScan = jdbcExplainForeignScan;
routine->ExplainForeignModify = jdbcExplainForeignModify;
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = jdbcAnalyzeForeignTable;
/* support for IMPORT FOREIGN SCHEMA */
routine->ImportForeignSchema = jdbcImportForeignSchema;
/* Support functions for upper relation push-down */
routine->GetForeignUpperPaths = jdbcGetForeignUpperPaths;
PG_RETURN_POINTER(routine);
}
Datum
jdbc_fdw_version(PG_FUNCTION_ARGS)
{
PG_RETURN_INT32(CODE_VERSION);
}
Datum
jdbc_exec(PG_FUNCTION_ARGS)
{
Jconn *conn = NULL;
char *servername = NULL;
char *sql = NULL;
Jresult *volatile res = NULL;
int resultSetID = 0;
TupleDesc tupleDescriptor;
PG_TRY();
{
if (PG_NARGS() == 2)
{
servername = text_to_cstring(PG_GETARG_TEXT_PP(0));
sql = text_to_cstring(PG_GETARG_TEXT_PP(1));
conn = jdbc_get_conn_by_server_name(servername);
}
else
{
/* shouldn't happen */
elog(ERROR, "jdbc_fdw: wrong number of arguments");
}
if (!conn)
{
ereport(ERROR,
(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
errmsg("jdbc_fdw: server \"%s\" not available", servername)));
}
prepTuplestoreResult(fcinfo);
/* Execute sql query */
res = jq_exec_id(conn, sql, &resultSetID);
if (*res != PGRES_COMMAND_OK)
jdbc_fdw_report_error(ERROR, res, conn, false, sql);
/* Create temp descriptor */
tupleDescriptor = jdbc_create_descriptor(conn, &resultSetID);
jq_iterate_all_row(fcinfo, conn, tupleDescriptor, resultSetID);
}
PG_FINALLY();
{
if (res)
jq_clear(res);
if (resultSetID != 0)
jq_release_resultset_id(conn, resultSetID);
tuplestore_donestoring((ReturnSetInfo *) fcinfo->resultinfo->setResult);
if (conn)
{
jdbc_release_connection(conn);
conn = NULL;
}
}
PG_END_TRY();
return (Datum) 0;
}
/*
* Verify function caller can handle a tuplestore result, and set up for that.
*
* Note: if the caller returns without actually creating a tuplestore, the
* executor will treat the function result as an empty set.
*/
static void
prepTuplestoreResult(FunctionCallInfo fcinfo)
{
ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
/* check to see if query supports us returning a tuplestore */
if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("set-valued function called in context that cannot accept a set")));
if (!(rsinfo->allowedModes & SFRM_Materialize))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("materialize mode required, but it is not allowed in this context")));
/* let the executor know we're sending back a tuplestore */
rsinfo->returnMode = SFRM_Materialize;
/* caller must fill these to return a non-empty result */
rsinfo->setResult = NULL;
rsinfo->setDesc = NULL;
}
/*
* jdbc_get_conn_by_server_name
* Get connection by the given server name
*/
static Jconn *
jdbc_get_conn_by_server_name(char *servername)
{
ForeignServer *foreign_server = NULL;
UserMapping *user_mapping;
Jconn *conn = NULL;
foreign_server = GetForeignServerByName(servername, false);
if (foreign_server)
{
Oid serverid = foreign_server->serverid;
Oid userid = GetUserId();
user_mapping = GetUserMapping(userid, serverid);
conn = jdbc_get_connection(foreign_server, user_mapping, false);
}
return conn;
}
/*
* jdbc_create_descriptor
* Create TypleDesc from result set
*/
static TupleDesc
jdbc_create_descriptor(Jconn *conn, int *resultSetID)
{
TupleDesc desc;
List *column_info_list;
ListCell *column_lc;
int column_num = 0;
int att_num = 0;
column_info_list = jq_get_column_infos_without_key(conn, resultSetID, &column_num);
desc = CreateTemplateTupleDesc(column_num);
foreach(column_lc, column_info_list)
{
JcolumnInfo *column_info = (JcolumnInfo *) lfirst(column_lc);
/* get oid from type name of column */
Oid tmpOid = jdbc_convert_type_name(column_info->column_type);
TupleDescInitEntry(desc, att_num + 1, NULL, tmpOid, -1, 0);
att_num++;
}
return BlessTupleDesc(desc);
}
/*
* Given a type name expressed as a string, look it up and return Oid
*/
static Oid
jdbc_convert_type_name(char *typname)
{
Oid oid;
oid = DatumGetObjectId(DirectFunctionCall1(regtypein,
CStringGetDatum(typname)));
if (!OidIsValid(oid))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("type \"%s\" does not exist", typname)));
return oid;
}
/*
* jdbcGetForeignRelSize Estimate # of rows and width of the result of the
* scan
*
* We should consider the effect of all baserestrictinfo clauses here, but
* not any join clauses.
*/
static void
jdbcGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
jdbcFdwRelationInfo *fpinfo;
ListCell *lc;
RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
Oid userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
Jconn *conn;
/* TODO: remove this functionality and support for remote statistics */
ereport(DEBUG3, (errmsg("In jdbcGetForeignRelSize")));
/*
* We use jdbcFdwRelationInfo to pass various information to subsequent
* functions.
*/
fpinfo = (jdbcFdwRelationInfo *) palloc0(sizeof(jdbcFdwRelationInfo));
baserel->fdw_private = (void *) fpinfo;
/* Base foreign tables need to be pushed down always. */
fpinfo->pushdown_safe = true;
/* Look up foreign-table catalog info. */
fpinfo->table = GetForeignTable(foreigntableid);
fpinfo->server = GetForeignServer(fpinfo->table->serverid);
/*
* Extract user-settable option values. Note that per-table setting of
* use_remote_estimate overrides per-server setting.
*/
fpinfo->use_remote_estimate = false;
fpinfo->fdw_startup_cost = DEFAULT_FDW_STARTUP_COST;
fpinfo->fdw_tuple_cost = DEFAULT_FDW_TUPLE_COST;
foreach(lc, fpinfo->server->options)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, "use_remote_estimate") == 0)
fpinfo->use_remote_estimate = defGetBoolean(def);
else if (strcmp(def->defname, "fdw_startup_cost") == 0)
(void) parse_real(defGetString(def), &fpinfo->fdw_startup_cost, 0,
NULL);
else if (strcmp(def->defname, "fdw_tuple_cost") == 0)
(void) parse_real(defGetString(def), &fpinfo->fdw_tuple_cost, 0,
NULL);
}
foreach(lc, fpinfo->table->options)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, "use_remote_estimate") == 0)
fpinfo->use_remote_estimate = defGetBoolean(def);
}
/*
* If the table or the server is configured to use remote estimates,
* identify which user to do remote access as during planning. This
* should match what ExecCheckRTEPerms() does. If we fail due to lack of
* permissions, the query would have failed at runtime anyway. And use
* user idenfifier for get default indentifier quote from remote server.
*/
fpinfo->user = GetUserMapping(userid, fpinfo->server->serverid);
conn = jdbc_get_connection(fpinfo->server, fpinfo->user, false);
/*
* Identify which baserestrictinfo clauses can be sent to the remote
* server and which can't.
*/
jdbc_classify_conditions(root, baserel, baserel->baserestrictinfo,
&fpinfo->remote_conds, &fpinfo->local_conds);
/*
* Identify which attributes will need to be retrieved from the remote
* server. These include all attrs needed for joins or final output, plus
* all attrs used in the local_conds. (Note: if we end up using a
* parameterized scan, it's possible that some of the join clauses will be
* sent to the remote and thus we wouldn't really need to retrieve the
* columns used in them. Doesn't seem worth detecting that case though.)
*/
fpinfo->attrs_used = NULL;
#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);
}
/*
* Compute the selectivity and cost of the local_conds, so we don't have
* to do it over again for each path. The best we can do for these
* conditions is to estimate selectivity on the basis of local statistics.
*/
fpinfo->local_conds_sel = clauselist_selectivity(root,
fpinfo->local_conds,
baserel->relid,
JOIN_INNER,
NULL);
cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root);
/*
* If the table or the server is configured to use remote estimates,
* connect to the foreign server and execute EXPLAIN to estimate the
* number of rows selected by the restriction clauses, as well as the
* average row width. Otherwise, estimate using whatever statistics we
* have locally, in a way similar to ordinary tables.
*/
if (fpinfo->use_remote_estimate)
{
/*
* Get cost/size estimates with help of remote server. Save the
* values in fpinfo so we don't need to do it again to generate the
* basic foreign path.
*/
estimate_path_cost_size(root, baserel, NIL,
&fpinfo->rows, &fpinfo->width,
&fpinfo->startup_cost,
&fpinfo->total_cost, conn->q_char);
}
else
{
/*
* If the foreign table has never been ANALYZEd, it will have relpages
* and reltuples equal to zero, which most likely has nothing to do
* with reality. We can't do a whole lot about that if we're not
* allowed to consult the remote server, but we can use a hack similar
* to plancat.c's treatment of empty relations: use a minimum size
* estimate of 10 pages, and divide by the column-datatype-based width
* estimate to get the corresponding number of tuples.
*/
#if PG_VERSION_NUM < 140000
if (baserel->pages == 0 && baserel->tuples == 0)
#else
if (baserel->tuples < 0)
#endif
{
baserel->pages = 10;
baserel->tuples =
(10 * BLCKSZ) / (baserel->reltarget->width + sizeof(HeapTupleHeaderData));
}
/*
* Estimate baserel size as best we can with local statistics.
*/
set_baserel_size_estimates(root, baserel);
/* Fill in basically-bogus cost estimates for use later. */
estimate_path_cost_size(root, baserel, NIL,
&fpinfo->rows, &fpinfo->width,
&fpinfo->startup_cost,
&fpinfo->total_cost, conn->q_char);
}
}
/*
* jdbcGetForeignPaths Create possible scan paths for a scan on the foreign
* table
*/
static void
jdbcGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
jdbcFdwRelationInfo *fpinfo = (jdbcFdwRelationInfo *) baserel->fdw_private;
ereport(DEBUG3, (errmsg("In jdbcGetForeignPaths")));
/*
* Create simplest ForeignScan path node and add it to baserel. This path
* corresponds to SeqScan path of regular tables (though depending on what
* baserestrict conditions we were able to send to remote, there might
* actually be an indexscan happening there). We already did all the work
* to estimate cost and size of this path.
*/
add_path(baserel, (Path *)
create_foreignscan_path(root, baserel,
#if PG_VERSION_NUM >= 90600
NULL, /* default pathtarget */
#endif
fpinfo->rows,
fpinfo->startup_cost,
fpinfo->total_cost,
NIL, /* no pathkeys */
baserel->lateral_relids,
NULL, /* no extra plan */
NULL)); /* no fdw_private data */
return;
}
/*
* jdbcGetForeignPlan Create ForeignScan plan node which implements selected
* best path
*/
static ForeignScan *
jdbcGetForeignPlan(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses,
Plan *outer_plan
)
{
jdbcFdwRelationInfo *fpinfo = (jdbcFdwRelationInfo *) baserel->fdw_private;
Index scan_relid = baserel->relid;
List *fdw_private;
List *remote_conds = NIL;
List *remote_exprs = NIL;
List *local_exprs = NIL;
List *params_list = NIL;
List *retrieved_attrs;
StringInfoData sql;
ListCell *lc;
int for_update = 0;
List *fdw_scan_tlist = NIL;
List *fdw_recheck_quals = NIL;
bool has_limit = false;
Jconn *conn;
ereport(DEBUG3, (errmsg("In jdbcGetForeignPlan")));
/*
* Get FDW private data created by griddbGetForeignUpperPaths(), if any.
*/
if (best_path->fdw_private)
{
#if PG_VERSION_NUM >= 150000
has_limit = boolVal(list_nth(best_path->fdw_private, FdwPathPrivateHasLimit));
#else
has_limit = intVal(list_nth(best_path->fdw_private, FdwPathPrivateHasLimit));
#endif
}
/*
* 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 jdbc_classify_conditions 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 jdbcGetForeignPaths. 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 jdbc_append_where_clause expects a list of
* RestrictInfos.
*/
if ((baserel->reloptkind == RELOPT_BASEREL ||
baserel->reloptkind == RELOPT_OTHER_MEMBER_REL)
)
{
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);
remote_exprs = lappend(remote_exprs, rinfo->clause);
}
else if (list_member_ptr(fpinfo->local_conds, rinfo))
local_exprs = lappend(local_exprs, rinfo->clause);
else if (jdbc_is_foreign_expr(root, baserel, rinfo->clause))
{
remote_conds = lappend(remote_conds, rinfo);
remote_exprs = lappend(remote_exprs, rinfo->clause);
}
else
local_exprs = lappend(local_exprs, rinfo->clause);
}
/*
* For a base-relation scan, we have to support EPQ recheck, which
* should recheck all the remote quals.
*/
fdw_recheck_quals = remote_exprs;
}
else
{
/*
* Join relation or upper relation - set scan_relid to 0.
*/
scan_relid = 0;
/*
* For a join rel, baserestrictinfo is NIL and we are not considering
* parameterization right now, so there should be no scan_clauses for
* a joinrel or an upper rel either.
*/
Assert(!scan_clauses);
/*
* Instead we get the conditions to apply from the fdw_private
* structure.
*/
remote_exprs = extract_actual_clauses(fpinfo->remote_conds, false);
local_exprs = extract_actual_clauses(fpinfo->local_conds, false);
/*
* We leave fdw_recheck_quals empty in this case, since we never need
* to apply EPQ recheck clauses. In the case of a joinrel, EPQ
* recheck is handled elsewhere --- see GetForeignJoinPaths(). If
* we're planning an upperrel (ie, remote grouping or aggregation)
* then there's no EPQ to do because SELECT FOR UPDATE wouldn't be
* allowed, and indeed we *can't* put the remote clauses into
* fdw_recheck_quals because the unaggregated Vars won't be available
* locally.
*/
/*
* Build the list of columns to be fetched from the foreign server.
*/
fdw_scan_tlist = jdbc_build_tlist_to_deparse(baserel);
/*
* Ensure that the outer plan produces a tuple whose descriptor
* matches our scan tuple slot. Also, remove the local conditions
* from outer plan's quals, lest they be evaluated twice, once by the
* local plan and once by the scan.
*/
if (outer_plan)
{
ListCell *lc;
/*
* Right now, we only consider grouping and aggregation beyond
* joins. Queries involving aggregates or grouping do not require
* EPQ mechanism, hence should not have an outer plan here.
*/
Assert(!IS_UPPER_REL(baserel));
/*
* First, update the plan's qual list if possible. In some cases
* the quals might be enforced below the topmost plan level, in
* which case we'll fail to remove them; it's not worth working
* harder than this.
*/
foreach(lc, local_exprs)
{
Node *qual = lfirst(lc);
outer_plan->qual = list_delete(outer_plan->qual, qual);
/*
* For an inner join the local conditions of foreign scan plan
* can be part of the joinquals as well. (They might also be
* in the mergequals or hashquals, but we can't touch those
* without breaking the plan.)
*/
if (IsA(outer_plan, NestLoop) ||
IsA(outer_plan, MergeJoin) ||
IsA(outer_plan, HashJoin))
{
Join *join_plan = (Join *) outer_plan;
if (join_plan->jointype == JOIN_INNER)
join_plan->joinqual = list_delete(join_plan->joinqual,
qual);
}
}
/*
* Now fix the subplan's tlist --- this might result in inserting
* a Result node atop the plan tree.
*/
outer_plan = change_plan_targetlist(outer_plan, fdw_scan_tlist,
best_path->path.parallel_safe);
}
}
conn = jdbc_get_connection(fpinfo->server, fpinfo->user, false);
/*
* Build the query string to be sent for execution, and identify
* expressions to be sent as parameters.
*/
initStringInfo(&sql);
jdbc_deparse_select_stmt_for_rel(&sql, root, baserel, remote_conds,
best_path->path.pathkeys,
&retrieved_attrs, ¶ms_list, fdw_scan_tlist,
has_limit, false, NIL, NIL, conn->q_char);
ereport(DEBUG3, (errmsg("SQL: %s", sql.data)));
/*
* Add FOR UPDATE/SHARE if appropriate. We apply locking during the
* initial row fetch, rather than later on as is done for local tables.