forked from laurenz/oracle_fdw
-
Notifications
You must be signed in to change notification settings - Fork 2
/
oracle_fdw.c
12795 lines (11200 loc) · 368 KB
/
oracle_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
/*-------------------------------------------------------------------------
*
* oracle_fdw.c
* PostgreSQL-related functions for Oracle foreign data wrapper.
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "fmgr.h"
#include "access/htup_details.h"
#include "access/reloptions.h"
#include "access/sysattr.h"
#include "access/xact.h"
#include "catalog/pg_aggregate.h"
#include "catalog/indexing.h"
#include "catalog/pg_attribute.h"
#include "catalog/pg_cast.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_foreign_data_wrapper.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_proc.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 "funcapi.h"
#if PG_VERSION_NUM < 100000
#include "libpq/md5.h"
#else
#include "common/md5.h"
#endif /* PG_VERSION_NUM */
#include "libpq/pqsignal.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/pg_list.h"
#if PG_VERSION_NUM <= 1340000
#include "optimizer/clauses.h"
#endif
#include "optimizer/cost.h"
#if PG_VERSION_NUM >= 140000
#include "optimizer/appendinfo.h"
#endif /* PG_VERSION_NUM */
#include "optimizer/pathnode.h"
#if PG_VERSION_NUM >= 130000
#include "optimizer/paths.h"
#endif /* PG_VERSION_NUM */
#include "optimizer/inherit.h"
#include "optimizer/planmain.h"
#include "optimizer/prep.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/tlist.h"
#include "parser/parse_relation.h"
#include "parser/parsetree.h"
#include "port.h"
#include "storage/ipc.h"
#include "storage/lock.h"
#include "tcop/tcopprot.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
#include "utils/date.h"
#include "utils/datetime.h"
#include "utils/elog.h"
#include "utils/fmgroids.h"
#include "utils/formatting.h"
#include "utils/float.h"
#include "utils/guc.h"
#include "utils/varlena.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/resowner.h"
#include "utils/timestamp.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/selfuncs.h"
#include "utils/typcache.h"
#if PG_VERSION_NUM < 120000
#include "nodes/relation.h"
#include "optimizer/var.h"
#include "utils/tqual.h"
#else
#include "nodes/pathnodes.h"
#include "optimizer/optimizer.h"
#include "access/heapam.h"
#endif
#include <string.h>
#include <stdlib.h>
#include "oracle_fdw.h"
/* defined in backend/commands/analyze.c */
#ifndef WIDTH_THRESHOLD
#define WIDTH_THRESHOLD 1024
#endif /* WIDTH_THRESHOLD */
#if PG_VERSION_NUM >= 90500
#define IMPORT_API
/* array_create_iterator has a new signature from 9.5 on */
#define array_create_iterator(arr, slice_ndim) array_create_iterator(arr, slice_ndim, NULL)
#else
#undef IMPORT_API
#endif /* PG_VERSION_NUM */
#if PG_VERSION_NUM >= 90600
#define JOIN_API
/* the useful macro IS_SIMPLE_REL is defined in v10, backport */
#ifndef IS_SIMPLE_REL
#define IS_SIMPLE_REL(rel) \
((rel)->reloptkind == RELOPT_BASEREL || \
(rel)->reloptkind == RELOPT_OTHER_MEMBER_REL)
#endif
/* GetConfigOptionByName has a new signature from 9.6 on */
#define GetConfigOptionByName(name, varname) GetConfigOptionByName(name, varname, false)
#else
#undef JOIN_API
#endif /* PG_VERSION_NUM */
#if PG_VERSION_NUM < 110000
/* backport macro from V11 */
#define TupleDescAttr(tupdesc, i) ((tupdesc)->attrs[(i)])
#endif /* PG_VERSION_NUM */
/* list API has changed in v13 */
#if PG_VERSION_NUM < 130000
#define list_next(l, e) lnext((e))
#define do_each_cell(cell, list, element) for_each_cell(cell, (element))
#else
#define list_next(l, e) lnext((l), (e))
#define do_each_cell(cell, list, element) for_each_cell(cell, (list), (element))
#endif /* PG_VERSION_NUM */
/* "table_open" was "heap_open" before v12 */
#if PG_VERSION_NUM < 120000
#define table_open(x, y) heap_open(x, y)
#define table_close(x, y) heap_close(x, y)
#endif /* PG_VERSION_NUM */
#if PG_VERSION_NUM <= 134000
/* source-code-compatibility hacks for pull_varnos() API change */
#define make_restrictinfo(a,b,c,d,e,f,g,h,i) make_restrictinfo_new(a,b,c,d,e,f,g,h,i)
#endif
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
/* If no remote estimates, assume a sort costs 20% extra */
#define DEFAULT_FDW_SORT_MULTIPLIER 1.2
/*
* "true" if Oracle data have been modified in the current transaction.
*/
static bool dml_in_transaction = false;
/*
* PostGIS geometry type, set upon library initialization.
*/
static Oid GEOMETRYOID = InvalidOid;
static bool geometry_is_setup = false;
/*
* OracleSupportedBuiltinAggFunction
* List of supported builtin aggregate functions for Oracle
*/
static const char *OracleSupportedBuiltinAggFunction[] = {
"sum",
"avg",
"max",
"min",
"stddev",
"count",
"variance",
"corr",
"covar_pop",
"covar_samp",
"cume_dist",
"dense_rank",
"percent_rank",
"stddev_pop",
"stddev_samp",
"var_pop",
"var_samp",
"percentile_cont",
"percentile_disc",
NULL};
/*
* OracleSupportedUniqueAggFunction
* List of supported unique aggregate functions for Oracle
*/
static const char *OracleUniqueAggFunction[] = {
"approx_count_distinct",
NULL};
/*
* OracleSupportedBuiltinNumericFunction
* List of supported builtin numeric functions for Oracle
*/
static const char *OracleSupportedBuiltinNumericFunction[] = {
"abs",
"acos",
"asin",
"atan",
"atan2",
"ceil",
"ceiling",
"cos",
"cosh",
"exp",
"floor",
"ln",
"log",
"mod",
"pow",
"power",
"round",
"sign",
"sin",
"sinh",
"sqrt",
"tan",
"tanh",
NULL};
/*
* OracleSupportedUniqueNumericFunction
* List of supported unique numeric functions for Oracle
*/
static const char *OracleUniqueNumericFunction[] = {
"oracle_round",
NULL};
/*
* OracleSupportedBuiltinStringFunction
* List of supported builtin string functions for Oracle
*/
static const char *OracleSupportedBuiltinStringFunction[] = {
"ascii",
"char_length",
"character_length",
"chr",
"initcap",
"length",
"lower",
"lpad",
"ltrim",
"octet_length",
"position",
"replace",
"rpad",
"rtrim",
"regexp_replace",
"strpos",
"substr",
"substring",
"translate",
"trunc",
"upper",
"width_bucket",
"to_char",
"to_date",
"to_number",
"to_timestamp",
NULL};
/*
* OracleUniqueDateTimeFunction
* List of unique Date/Time function for Oracle
*/
static const char *OracleUniqueDateTimeFunction[] = {
"add_months",
"last_day",
"oracle_current_date",
"oracle_current_timestamp",
"oracle_localtimestamp",
"oracle_extract",
"dbtimezone",
"from_tz",
"months_between",
"new_time",
"next_day",
"numtodsinterval",
"numtoyminterval",
NULL};
/*
* Describes the valid options for objects that use this wrapper.
*/
struct OracleFdwOption
{
const char *optname;
Oid optcontext; /* Oid of catalog in which option may appear */
bool optrequired;
};
typedef struct pull_func_clause_context
{
List *funclist;
} pull_func_clause_context;
/*
* Context for deparseExpr
*/
typedef struct deparse_expr_cxt
{
PlannerInfo *root; /* global planner state */
RelOptInfo *foreignrel; /* the foreign relation we are planning for */
RelOptInfo *scanrel; /* the underlying scan relation. Same as
* foreignrel, when that represents a join or
* a base relation. */
StringInfo buf; /* output buffer to append to */
List **params_list; /* exprs that will become remote Params */
oracleSession *session; /* encapsulates the active Oracle session */
struct oraTable *oraTable; /* description of the remote Oracle table */
bool use_alias; /* mark alias use */
Index ignore_rel; /* is either zero or the RT index of a target relation.
* Use for deparsing join relation */
List **ignore_conds; /* List of join clause. Use for deparsing join relation */
bool string_comparison; /* mark if handling string comparison */
bool handle_length_func; /* mark if handling length function */
bool can_pushdown_function; /* true if query contains function
* which can pushed down to remote server */
bool handle_aggref; /* mark if handling aggregation */
} deparse_expr_cxt;
typedef struct oracle_default_const_ctx
{
Const *c;
} oracle_default_const_ctx;
#define OPT_NLS_LANG "nls_lang"
#define OPT_DBSERVER "dbserver"
#define OPT_ISOLATION_LEVEL "isolation_level"
#define OPT_NCHAR "nchar"
#define OPT_USER "user"
#define OPT_PASSWORD "password"
#define OPT_DBLINK "dblink"
#define OPT_SCHEMA "schema"
#define OPT_TABLE "table"
#define OPT_MAX_LONG "max_long"
#define OPT_READONLY "readonly"
#define OPT_KEY "key"
#define OPT_STRIP_ZEROS "strip_zeros"
#define OPT_SAMPLE "sample_percent"
#define OPT_PREFETCH "prefetch"
#define OPT_COLUMN_NAME "column_name"
#define DEFAULT_ISOLATION_LEVEL ORA_TRANS_SERIALIZABLE
#define DEFAULT_MAX_LONG 32767
#define DEFAULT_PREFETCH 200
/*
* Options for case folding for names in IMPORT FOREIGN TABLE.
*/
typedef enum { CASE_KEEP, CASE_LOWER, CASE_SMART } fold_t;
/*
* Valid options for oracle_fdw.
*/
static struct OracleFdwOption valid_options[] = {
{OPT_NLS_LANG, ForeignDataWrapperRelationId, false},
{OPT_DBSERVER, ForeignServerRelationId, true},
{OPT_ISOLATION_LEVEL, ForeignServerRelationId, false},
{OPT_NCHAR, ForeignServerRelationId, false},
{OPT_USER, UserMappingRelationId, true},
{OPT_PASSWORD, UserMappingRelationId, true},
{OPT_DBLINK, ForeignTableRelationId, false},
{OPT_SCHEMA, ForeignTableRelationId, false},
{OPT_TABLE, ForeignTableRelationId, true},
{OPT_MAX_LONG, ForeignTableRelationId, false},
{OPT_READONLY, ForeignTableRelationId, false},
{OPT_SAMPLE, ForeignTableRelationId, false},
{OPT_PREFETCH, ForeignTableRelationId, false},
{OPT_COLUMN_NAME, AttributeRelationId, false},
{OPT_KEY, AttributeRelationId, false},
{OPT_STRIP_ZEROS, AttributeRelationId, false}
};
#define option_count (sizeof(valid_options)/sizeof(struct OracleFdwOption))
/*
* Array to hold the type output functions during table modification.
* It is ok to hold this cache in a static variable because there cannot
* be more than one foreign table modified at the same time.
*/
static regproc *output_funcs;
/*
* FDW-specific information for RelOptInfo.fdw_private and ForeignScanState.fdw_state.
* The same structure is used to hold information for query planning and execution.
* The structure is initialized during query planning and passed on to the execution
* step serialized as a List (see serializePlanData and deserializePlanData).
* For DML statements, the scan stage and the modify stage both hold an
* OracleFdwState, and the latter is initialized by copying the former (see copyPlanData).
*/
struct OracleFdwState {
char *dbserver; /* Oracle connect string */
oraIsoLevel isolation_level; /* Transaction Isolation Level */
char *user; /* Oracle username */
char *password; /* Oracle password */
char *nls_lang; /* Oracle locale information */
bool have_nchar; /* needs support for national character conversion */
oracleSession *session; /* encapsulates the active Oracle session */
char *query; /* query we issue against Oracle */
List *params; /* list of parameters needed for the query */
struct paramDesc *paramList; /* description of parameters needed for the query */
struct oraTable *oraTable; /* description of the remote Oracle table */
Cost startup_cost; /* cost estimate, only needed for planning */
Cost total_cost; /* cost estimate, only needed for planning */
unsigned long rowcount; /* rows already read from Oracle */
int columnindex; /* currently processed column for error context */
MemoryContext temp_cxt; /* short-lived memory for data modification */
unsigned int prefetch; /* number of rows to prefetch */
char *order_clause; /* for ORDER BY pushdown */
List *usable_pathkeys; /* for ORDER BY pushdown */
char *where_clause; /* deparsed where clause */
char *limit_clause; /* deparsed limit clause */
/* FOR FOREIGN SCAN and FOREIGN MODIFICATION */
/*
* Restriction clauses, divided into safe and unsafe to pushdown subsets.
*
* For a base foreign relation this is a list of clauses along-with
* RestrictInfo wrapper. Keeping RestrictInfo wrapper helps while dividing
* scan_clauses in oracleGetForeignPlan into safe and unsafe subsets.
* Also it helps in estimating costs since RestrictInfo caches the
* selectivity and qual cost for the clause in it.
*
* For a join relation, however, they are part of otherclause list
* obtained from extract_actual_join_clauses, which strips RestrictInfo
* construct. So, for a join relation they are list of bare clauses.
*/
List *remote_conds; /* can be pushed down to remote server */
List *local_conds; /* cannot be pushed down to remote server */
/* Join information */
RelOptInfo *outerrel;
RelOptInfo *innerrel;
JoinType jointype;
List *joinclauses;
long max_long; /* use this for re-build oraTable */
List *retrieved_attrs; /* attr numbers retrieved by RETURNING */
/* RELATION INFO */
/*
* True means that the relation can be pushed down. Always true for simple
* foreign scan.
*/
bool pushdown_safe;
/* Actual remote restriction clauses for scan (sans RestrictInfos) */
List *final_remote_exprs;
/* Bitmap of attr numbers we need to fetch from the remote server. */
Bitmapset *attrs_used;
/* True means that the query_pathkeys is safe to push down */
bool qp_is_pushdown_safe;
/* Cost and selectivity of local_conds. */
QualCost local_conds_cost;
Selectivity local_conds_sel;
/* Estimated size and cost for a scan, join, or grouping/aggregation. */
double rows;
int width;
/*
* Estimated number of rows fetched from the foreign server, and costs
* excluding costs for transferring those rows from the foreign server.
* These are only used by estimate_path_cost_size().
*/
double retrieved_rows;
Cost rel_startup_cost;
Cost rel_total_cost;
/* Options extracted from catalogs. */
Cost fdw_startup_cost;
Cost fdw_tuple_cost;
/* Cached catalog information. */
ForeignTable *table;
ForeignServer *server;
/*
* Name of the relation, for use while EXPLAINing ForeignScan. It is used
* for join and upper relations but is set for all relations. For a base
* relation, this is really just the RT index as a string; we convert that
* while producing EXPLAIN output. For join and upper relations, the name
* indicates which base foreign tables are included and the join type or
* aggregation type used.
*/
char *relation_name;
/* Upper relation information */
UpperRelationKind stage;
/* Grouping information */
List *grouped_tlist;
/* Subquery information */
bool make_outerrel_subquery; /* do we deparse outerrel as a
* subquery? */
bool make_innerrel_subquery; /* do we deparse innerrel as a
* subquery? */
Relids lower_subquery_rels; /* all relids appearing in lower
* subqueries */
/*
* Index of the relation. It is used to create an alias to a subquery
* representing the relation.
*/
int relation_index;
/* Function pushdown support in target list */
bool is_tlist_func_pushdown;
/* scan tlist */
List *fdw_scan_tlist;
/* FOR DIRECT MODIFICATION */
Relation rel; /* relcache entry for the foreign table */
/* extracted fdw_private data */
bool has_returning; /* is there a RETURNING clause? */
bool set_processed; /* do we set the command es_processed? */
int numParams; /* number of parameters passed to query */
/* for storing result tuples */
int next_tuple; /* index of next one to return */
Relation resultRel; /* relcache entry for the target relation */
AttrNumber *attnoMap; /* array of attnums of input user columns */
};
/*
* 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
};
/* Struct for extra information passed to estimate_path_cost_size() */
typedef struct
{
PathTarget *target;
bool has_final_sort;
bool has_limit;
double limit_tuples;
int64 count_est;
int64 offset_est;
} OracleFdwPathExtraData;
/*
* SQL functions
*/
extern PGDLLEXPORT Datum oracle_fdw_handler(PG_FUNCTION_ARGS);
extern PGDLLEXPORT Datum oracle_fdw_validator(PG_FUNCTION_ARGS);
extern PGDLLEXPORT Datum oracle_close_connections(PG_FUNCTION_ARGS);
extern PGDLLEXPORT Datum oracle_diag(PG_FUNCTION_ARGS);
extern PGDLLEXPORT Datum oracle_execute(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(oracle_fdw_handler);
PG_FUNCTION_INFO_V1(oracle_fdw_validator);
PG_FUNCTION_INFO_V1(oracle_close_connections);
PG_FUNCTION_INFO_V1(oracle_diag);
PG_FUNCTION_INFO_V1(oracle_execute);
/*
* on-load initializer
*/
extern PGDLLEXPORT void _PG_init(void);
/*
* FDW callback routines
*/
static void oracleGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid);
static void oracleGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid);
#ifdef JOIN_API
static void oracleGetForeignJoinPaths(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, JoinPathExtraData *extra);
#endif /* JOIN_API */
static ForeignScan *oracleGetForeignPlan(PlannerInfo *root, RelOptInfo *foreignrel, Oid foreigntableid, ForeignPath *best_path, List *tlist, List *scan_clauses
#if PG_VERSION_NUM >= 90500
, Plan *outer_plan
#endif /* PG_VERSION_NUM */
);
static bool oracleAnalyzeForeignTable(Relation relation, AcquireSampleRowsFunc *func, BlockNumber *totalpages);
static void oracleExplainForeignScan(ForeignScanState *node, ExplainState *es);
static void oracleBeginForeignScan(ForeignScanState *node, int eflags);
static TupleTableSlot *oracleIterateForeignScan(ForeignScanState *node);
static void oracleEndForeignScan(ForeignScanState *node);
static void oracleReScanForeignScan(ForeignScanState *node);
#if PG_VERSION_NUM < 140000
static void oracleAddForeignUpdateTargets(Query *parsetree, RangeTblEntry *target_rte, Relation target_relation);
#else
static void oracleAddForeignUpdateTargets(PlannerInfo *root, Index rtindex, RangeTblEntry *target_rte, Relation target_relation);
#endif
static List *oraclePlanForeignModify(PlannerInfo *root, ModifyTable *plan, Index resultRelation, int subplan_index);
static void oracleBeginForeignModify(ModifyTableState *mtstate, ResultRelInfo *rinfo, List *fdw_private, int subplan_index, int eflags);
#if PG_VERSION_NUM >= 110000
static void oracleBeginForeignInsert(ModifyTableState *mtstate, ResultRelInfo *rinfo);
static void oracleEndForeignInsert(EState *estate, ResultRelInfo *rinfo);
#endif /*PG_VERSION_NUM */
static TupleTableSlot *oracleExecForeignInsert(EState *estate, ResultRelInfo *rinfo, TupleTableSlot *slot, TupleTableSlot *planSlot);
static TupleTableSlot *oracleExecForeignUpdate(EState *estate, ResultRelInfo *rinfo, TupleTableSlot *slot, TupleTableSlot *planSlot);
static TupleTableSlot *oracleExecForeignDelete(EState *estate, ResultRelInfo *rinfo, TupleTableSlot *slot, TupleTableSlot *planSlot);
static void oracleEndForeignModify(EState *estate, ResultRelInfo *rinfo);
static void oracleExplainForeignModify(ModifyTableState *mtstate, ResultRelInfo *rinfo, List *fdw_private, int subplan_index, struct ExplainState *es);
static int oracleIsForeignRelUpdatable(Relation rel);
#ifdef IMPORT_API
static List *oracleImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid);
#endif /* IMPORT_API */
static void oracleGetForeignUpperPaths(PlannerInfo *root,
UpperRelationKind stage,
RelOptInfo *input_rel,
RelOptInfo *output_rel,
void *extra);
static bool oraclePlanDirectModify(PlannerInfo *root,
ModifyTable *plan,
Index resultRelation,
int subplan_index);
static void oracleBeginDirectModify(ForeignScanState *node, int eflags);
static TupleTableSlot *oracleIterateDirectModify(ForeignScanState *node);
static void oracleEndDirectModify(ForeignScanState *node);
static void oracleExplainDirectModify(ForeignScanState *node,
ExplainState *es);
/*
* Helper functions
*/
static struct OracleFdwState *getFdwState(Oid foreigntableid, double *sample_percent, Oid userid);
static void oracleGetOptions(Oid foreigntableid, Oid userid, List **options);
static void deparseFromExprForRel(StringInfo buf, RelOptInfo *joinrel, List **params_list, deparse_expr_cxt *context);
#ifdef JOIN_API
static void appendConditions(List *exprs, deparse_expr_cxt *context);
static bool foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinPathExtraData *extra);
static const char *get_jointype_name(JoinType jointype);
static List *build_tlist_to_deparse(RelOptInfo *foreignrel);
#endif /* JOIN_API */
static void getColumnData(Oid foreigntableid, struct oraTable *oraTable);
static void getColumnDataByTupdesc(Relation rel, TupleDesc tupdesc, List *retrieved_attrs, struct oraTable *oraTable);
static int acquireSampleRowsFunc (Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows);
static void appendAsType(StringInfoData *dest, const char *s, Oid type);
static void castNullAsType(StringInfoData *dest, Oid type);
static char *deparseExpr(Expr *node, deparse_expr_cxt *context);
static char *datumToString(Datum datum, Oid type);
static void getUsedColumns(Expr *expr, struct oraTable *oraTable, int foreignrelid);
static void checkDataType(oraType oratype, int scale, Oid pgtype, const char *tablename, const char *colname);
static char *deparseWhereConditions(struct OracleFdwState *fdwState, PlannerInfo *root, RelOptInfo *baserel, List **local_conds, List **remote_conds);
static char *guessNlsLang(char *nls_lang);
static oracleSession *oracleConnectServer(Name srvname);
static List *serializePlanData(struct OracleFdwState *fdwState, struct oraTable *oraTable);
static Const *serializeString(const char *s);
static Const *serializeLong(long i);
static struct OracleFdwState *deserializePlanData(List *list);
static char *deserializeString(Const *constant);
static long deserializeLong(Const *constant);
static bool optionIsTrue(const char *value);
#if PG_VERSION_NUM < 130000
/* this function is not exported before v13 */
static Expr *find_em_expr_for_rel(EquivalenceClass *ec, RelOptInfo *rel);
#endif /* PG_VERSION_NUM */
static char *deparseDate(Datum datum);
static char *deparseTimestamp(Datum datum, bool hasTimezone);
static char *deparseInterval(Datum datum);
static char *convertUUID(char *uuid);
static void subtransactionCallback(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg);
static void addParam(struct paramDesc **paramList, char *name, Oid pgtype, oraType oratype, int colnum);
static void setModifyParameters(struct paramDesc *paramList, TupleTableSlot *newslot, TupleTableSlot *oldslot, struct oraTable *oraTable, oracleSession *session);
static void transactionCallback(XactEvent event, void *arg);
static void exitHook(int code, Datum arg);
static void oracleDie(SIGNAL_ARGS);
static char *setSelectParameters(struct paramDesc *paramList, ExprContext *econtext);
static void convertTuple(struct OracleFdwState *fdw_state, Datum *values, bool *nulls, bool trunc_lob);
static void errorContextCallback(void *arg);
static bool hasTrigger(Relation rel, CmdType cmdtype);
static void buildInsertQuery(StringInfo sql, struct OracleFdwState *fdwState);
static void buildUpdateQuery(StringInfo sql, struct OracleFdwState *fdwState, List *targetAttrs);
static void appendReturningClause(StringInfo sql, struct OracleFdwState *fdwState);
#ifdef IMPORT_API
static char *fold_case(char *name, fold_t foldcase, int collation);
#endif /* IMPORT_API */
static oraIsoLevel getIsolationLevel(const char *isolation_level);
static char *deparseLimit(PlannerInfo *root, struct OracleFdwState *fdwState);
static void initializeContext(struct OracleFdwState *fdwState,
PlannerInfo *root,
RelOptInfo *foreignrel,
RelOptInfo *scanrel,
deparse_expr_cxt *context);
extern EquivalenceMember *find_em_for_rel(PlannerInfo *root,
EquivalenceClass *ec,
RelOptInfo *rel);
static EquivalenceMember *find_em_for_rel_target(PlannerInfo *root,
EquivalenceClass *ec,
RelOptInfo *rel);
static List *get_useful_pathkeys_for_relation(PlannerInfo *root,
RelOptInfo *rel);
static void add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel,
Path *epq_path);
static TupleDesc
get_tupdesc_for_join_scan_tuples(ForeignScanState *node);
static void add_foreign_grouping_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *grouped_rel,
GroupPathExtraData *extra);
static void add_foreign_ordered_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *ordered_rel);
static void add_foreign_final_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *final_rel,
FinalPathExtraData *extra);
static void merge_fdw_state(struct OracleFdwState * fpinfo,
const struct OracleFdwState * fpinfo_o,
const struct OracleFdwState * fpinfo_i);
static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel,
Node *havingQual);
static bool is_foreign_param(PlannerInfo *root, RelOptInfo *baserel, Expr *expr);
static void adjust_foreign_grouping_path_cost(PlannerInfo *root,
List *pathkeys,
double retrieved_rows,
double width,
double limit_tuples,
Cost *p_startup_cost,
Cost *p_run_cost);
static void estimate_path_cost_size(PlannerInfo *root,
RelOptInfo *foreignrel,
List *param_join_conds,
List *pathkeys,
OracleFdwPathExtraData *fpextra,
double *p_rows, int *p_width,
Cost *p_startup_cost, Cost *p_total_cost);
static bool exist_in_function_list(char *funcname, const char **funclist);
static void
oracleDeparseSelectStmtForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *rel,
List *tlist, List *remote_conds, bool for_update, List *pathkeys,
bool has_final_sort, bool has_limit, bool is_subquery,
List **retrieved_attrs, List **params_list);
static void
oracleDeparseSelectSql(List *tlist, bool is_subquery, List **retrieved_attrs,
deparse_expr_cxt *context);
static void
oracleDeparseSubqueryTargetList(deparse_expr_cxt *context);
static void
oracleDeparseExplicitTargetList(List *tlist,
bool is_returning,
List **retrieved_attrs,
deparse_expr_cxt *context);
static
void oracleDeparseReturningList(struct oraTable *oraTable, StringInfo buf, RangeTblEntry *rte,
Index rtindex, Relation rel,
bool trig_after_row,
List *withCheckOptionList,
List *returningList,
List **retrieved_attrs);
static void
oracleDeparseTargetList(struct oraTable *oraTable, StringInfo buf,
RangeTblEntry *rte,
Index rtindex,
Relation rel,
bool is_returning,
Bitmapset *attrs_used,
bool qualify_col,
List **retrieved_attrs);
static void
oracleDeparseColumnRef(struct oraTable *oraTable, StringInfo buf, int varno, int varattno, bool qualify_col);
static void
oracleDeparseFromExpr(struct OracleFdwState *fdwState, List *quals, deparse_expr_cxt *context);
static void
oracleDeparseRangeTblRef(StringInfo buf, RelOptInfo *foreignrel,
bool make_subquery, List **params_list, deparse_expr_cxt *context);
static void
oracleAppendGroupByClause(List *tlist, deparse_expr_cxt *context);
static char *
oracleAppendAggOrderBy(List *orderList, List *targetList,
deparse_expr_cxt *context);
static Node *
oracleDeparseSortGroupClause(Index ref, List *tlist,
deparse_expr_cxt *context);
static char *
oracleDeparseAggref(Aggref *node, deparse_expr_cxt *context);
static void
oracleAppendOrderByClause(List *pathkeys, bool has_final_sort,
deparse_expr_cxt *context);
static char *oracleCreateQuery(char *tablename);
static int set_transmission_modes(void);
static void reset_transmission_modes(int nestlevel);
static struct oraTable *getOraTableFromJoinRel(Var *variable, RelOptInfo *foreignrel);
static char *
oracleDeparseConcat(List *args, deparse_expr_cxt *context);
static bool
oracle_contain_functions_walker(Node *node, void *context);
static bool oracle_is_foreign_function_tlist(PlannerInfo *root,
RelOptInfo *baserel,
List *tlist);
static int set_transmission_modes(void);
static void reset_transmission_modes(int nestlevel);
static char *oracle_replace_function(char *in);
static bool starts_with(const char *pre, const char *str);
#if PG_VERSION_NUM >= 140000
static ForeignScan *find_modifytable_subplan(PlannerInfo *root,
ModifyTable *plan,
Index rtindex,
int subplan_index);
#endif
static List *build_remote_returning(Index rtindex, Relation rel, List *returningList);
static void rebuild_fdw_scan_tlist(ForeignScan *fscan, List *tlist);
static void oracleDeparseDirectUpdateSql(StringInfo buf, PlannerInfo *root,
Index rtindex, Relation rel,
RelOptInfo *foreignrel,
List *targetlist,
List *targetAttrs,
List *remote_conds,
List **params_list,
List *returningList,
List **retrieved_attrs);
static void oracleDeparseDirectDeleteSql(StringInfo buf, PlannerInfo *root,
Index rtindex, Relation rel,
RelOptInfo *foreignrel,
List *remote_conds,
List **params_list,
List *returningList,
List **retrieved_attrs);
static void init_returning_filter(struct OracleFdwState *dmstate,
List *fdw_scan_tlist,
Index rtindex);
static TupleTableSlot *apply_returning_filter(struct OracleFdwState *dmstate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
EState *estate);
static void prepare_query_params(struct OracleFdwState *fdw_state,
PlanState *node,
List *fdw_exprs,
int numParams);
static void execute_dml_stmt(ForeignScanState *node);
static TupleTableSlot *get_returning_data(ForeignScanState *node);
extern int
#if (PG_VERSION_NUM >=160000)
PGDLLEXPORT
#endif
ExecForeignDDL(Oid serverOid,
Relation rel,
int operation,
bool exists_flag);
static void oracleDeparseCreateTableSql(StringInfo buf, Relation rel, ForeignTable *foreigntable);
static void oracleDeparseDropTableSql(StringInfo buf, Relation rel);
static void oracleDeparseRelation(StringInfo buf, Relation rel);
static char *oracleDeparseTypeName(Oid type_oid, int32 typemod);
static char *oraclePrintTypmod(const char *typname, int32 typmod, Oid typmodout);
static bool oracle_get_default_const_walker(Node *node, oracle_default_const_ctx * ctx);
#define REL_ALIAS_PREFIX "r"
/* Handy macro to add relation name qualification */
#define ADD_REL_QUALIFIER(buf, varno) \
appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno))
#define SUBQUERY_REL_ALIAS_PREFIX "s"
#define SUBQUERY_COL_ALIAS_PREFIX "c"
/*
* Foreign-data wrapper handler function: return a struct with pointers
* to callback routines.
*/
PGDLLEXPORT Datum
oracle_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *fdwroutine = makeNode(FdwRoutine);
fdwroutine->GetForeignRelSize = oracleGetForeignRelSize;
fdwroutine->GetForeignPaths = oracleGetForeignPaths;
#ifdef JOIN_API
fdwroutine->GetForeignJoinPaths = oracleGetForeignJoinPaths;
#endif /* JOIN_API */
fdwroutine->GetForeignPlan = oracleGetForeignPlan;
fdwroutine->AnalyzeForeignTable = oracleAnalyzeForeignTable;
fdwroutine->ExplainForeignScan = oracleExplainForeignScan;
fdwroutine->BeginForeignScan = oracleBeginForeignScan;
fdwroutine->IterateForeignScan = oracleIterateForeignScan;
fdwroutine->ReScanForeignScan = oracleReScanForeignScan;
fdwroutine->EndForeignScan = oracleEndForeignScan;
fdwroutine->AddForeignUpdateTargets = oracleAddForeignUpdateTargets;
fdwroutine->PlanForeignModify = oraclePlanForeignModify;
fdwroutine->BeginForeignModify = oracleBeginForeignModify;
#if PG_VERSION_NUM >= 110000
fdwroutine->BeginForeignInsert = oracleBeginForeignInsert;
fdwroutine->EndForeignInsert = oracleEndForeignInsert;
#endif /*PG_VERSION_NUM */
fdwroutine->ExecForeignInsert = oracleExecForeignInsert;
fdwroutine->ExecForeignUpdate = oracleExecForeignUpdate;
fdwroutine->ExecForeignDelete = oracleExecForeignDelete;
fdwroutine->EndForeignModify = oracleEndForeignModify;
fdwroutine->ExplainForeignModify = oracleExplainForeignModify;
fdwroutine->IsForeignRelUpdatable = oracleIsForeignRelUpdatable;
#ifdef IMPORT_API
fdwroutine->ImportForeignSchema = oracleImportForeignSchema;
#endif /* IMPORT_API */
/* Support functions for upper relation push-down */
fdwroutine->GetForeignUpperPaths = oracleGetForeignUpperPaths;
/* Support direct modification */
fdwroutine->PlanDirectModify = oraclePlanDirectModify;
fdwroutine->BeginDirectModify = oracleBeginDirectModify;
fdwroutine->IterateDirectModify = oracleIterateDirectModify;
fdwroutine->EndDirectModify = oracleEndDirectModify;
fdwroutine->ExplainDirectModify = oracleExplainDirectModify;
PG_RETURN_POINTER(fdwroutine);
}
/*
* oracle_fdw_validator
* Validate the generic options given to a FOREIGN DATA WRAPPER, SERVER,
* USER MAPPING or FOREIGN TABLE that uses oracle_fdw.
*
* Raise an ERROR if the option or its value are considered invalid
* or a required option is missing.
*/
PGDLLEXPORT Datum
oracle_fdw_validator(PG_FUNCTION_ARGS)
{
List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
Oid catalog = PG_GETARG_OID(1);
ListCell *cell;
bool option_given[option_count] = { false };
int i;
/*