forked from laurenz/oracle_fdw
-
Notifications
You must be signed in to change notification settings - Fork 4
/
oracle_fdw.c
7358 lines (6493 loc) · 221 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/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"
/* for "hash_bytes_extended" or "hash_bytes" */
#if PG_VERSION_NUM >= 130000
#include "common/hashfn.h"
#elif PG_VERSION_NUM >= 120000
#include "utils/hashutils.h"
#else
#include "access/hash.h"
#endif /* PG_VERSION_NUM */
#if PG_VERSION_NUM < 110000
#define hash_bytes_extended(k, keylen, seed) \
DatumGetInt32(hash_any((k), (keylen)))
#elif PG_VERSION_NUM < 130000
#define hash_bytes_extended(k, keylen, seed) \
DatumGetInt64(hash_any_extended((k), (keylen), (seed)))
#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"
#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/inherit.h"
#include "optimizer/paths.h"
#endif /* PG_VERSION_NUM */
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/tlist.h"
#include "parser/parse_relation.h"
#include "parser/parsetree.h"
#include "pgtime.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/guc.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/timestamp.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 */
PG_MODULE_MAGIC;
/*
* "true" if Oracle data have been modified in the current transaction.
*/
static bool dml_in_transaction = false;
/*
* PostGIS geometry type, set in initializePostGIS().
*/
static Oid GEOMETRYOID = InvalidOid;
static bool geometry_is_setup = false;
/*
* 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;
};
#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_LOB_PREFETCH "lob_prefetch"
#define OPT_SET_TIMEZONE "set_timezone"
#define DEFAULT_ISOLATION_LEVEL ORA_TRANS_SERIALIZABLE
#define DEFAULT_MAX_LONG 32767
#define DEFAULT_PREFETCH 50
#define DEFAULT_LOB_PREFETCH 1048576
/*
* 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_LOB_PREFETCH, ForeignTableRelationId, false},
{OPT_KEY, AttributeRelationId, false},
{OPT_STRIP_ZEROS, AttributeRelationId, false},
{OPT_SET_TIMEZONE, ForeignServerRelationId, 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 */
char *timezone; /* session time zone */
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 int prefetch; /* number of rows to prefetch */
unsigned int lob_prefetch; /* number of LOB bytes to prefetch */
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 */
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 */
/*
* 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;
};
/*
* 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 */
/*
* Helper functions
*/
static struct OracleFdwState *getFdwState(Oid foreigntableid, double *sample_percent, Oid userid);
static void oracleGetOptions(Oid foreigntableid, Oid userid, List **options);
static char *createQuery(struct OracleFdwState *fdwState, RelOptInfo *foreignrel, bool for_update, List *query_pathkeys);
static void deparseFromExprForRel(struct OracleFdwState *fdwState, StringInfo buf, RelOptInfo *joinrel, List **params_list);
#ifdef JOIN_API
static void appendConditions(List *exprs, StringInfo buf, RelOptInfo *joinrel, List **params_list);
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);
static struct oraTable *build_join_oratable(struct OracleFdwState *fdwState, List *fdw_scan_tlist);
#endif /* JOIN_API */
static void getColumnData(Oid foreigntableid, 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 char *deparseExpr(oracleSession *session, RelOptInfo *foreignrel, Expr *expr, const struct oraTable *oraTable, List **params);
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, RelOptInfo *baserel, List **local_conds, List **remote_conds);
static char *guessNlsLang(char *nls_lang);
static char *getTimezone(void);
static oracleSession *oracleConnectServer(Name srvname);
static List *serializePlanData(struct OracleFdwState *fdwState);
static Const *serializeString(const char *s);
static struct OracleFdwState *deserializePlanData(List *list);
static char *deserializeString(Const *constant);
static bool optionIsTrue(const char *value);
static char *deparseDate(Datum datum);
static char *deparseTimestamp(Datum datum, bool hasTimezone);
static char *deparseInterval(Datum datum);
static char *convertUUID(char *uuid);
static struct OracleFdwState *copyPlanData(struct OracleFdwState *orig);
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, unsigned int index, 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 bool pushdownOrderBy(PlannerInfo *root, RelOptInfo *baserel, struct OracleFdwState *fdwState);
static char *deparseLimit(PlannerInfo *root, struct OracleFdwState *fdwState, RelOptInfo *baserel);
#if PG_VERSION_NUM < 150000
/* this is new in PostgreSQL v15 */
struct pg_itm
{
int tm_usec;
int tm_sec;
int tm_min;
int64 tm_hour; /* needs to be wide */
int tm_mday;
int tm_mon;
int tm_year;
};
static void interval2itm(Interval span, struct pg_itm *itm);
#endif /* PG_VERSION_NUM */
#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))
/*
* 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 */
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;
/*
* Check that only options supported by oracle_fdw, and allowed for the
* current object type, are given.
*/
foreach(cell, options_list)
{
DefElem *def = (DefElem *)lfirst(cell);
bool opt_found = false;
/* search for the option in the list of valid options */
for (i=0; i<option_count; ++i)
{
if (catalog == valid_options[i].optcontext && strcmp(valid_options[i].optname, def->defname) == 0)
{
opt_found = true;
option_given[i] = true;
break;
}
}
/* option not found, generate error message */
if (!opt_found)
{
/* generate list of options */
StringInfoData buf;
initStringInfo(&buf);
for (i=0; i<option_count; ++i)
{
if (catalog == valid_options[i].optcontext)
appendStringInfo(&buf, "%s%s", (buf.len > 0) ? ", " : "", valid_options[i].optname);
}
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
errmsg("invalid option \"%s\"", def->defname),
errhint("Valid options in this context are: %s", buf.data)));
}
/* check valid values for "isolation_level" */
if (strcmp(def->defname, OPT_ISOLATION_LEVEL) == 0)
(void)getIsolationLevel(strVal(def->arg));
/* check valid values for "readonly", "key", "strip_zeros" and "nchar" */
if (strcmp(def->defname, OPT_READONLY) == 0
|| strcmp(def->defname, OPT_KEY) == 0
|| strcmp(def->defname, OPT_STRIP_ZEROS) == 0
|| strcmp(def->defname, OPT_NCHAR) == 0
|| strcmp(def->defname, OPT_SET_TIMEZONE) == 0
)
{
char *val = strVal(def->arg);
if (pg_strcasecmp(val, "on") != 0
&& pg_strcasecmp(val, "off") != 0
&& pg_strcasecmp(val, "yes") != 0
&& pg_strcasecmp(val, "no") != 0
&& pg_strcasecmp(val, "true") != 0
&& pg_strcasecmp(val, "false") != 0)
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_ATTRIBUTE_VALUE),
errmsg("invalid value for option \"%s\"", def->defname),
errhint("Valid values in this context are: on/yes/true or off/no/false")));
}
/* check valid values for "dblink" */
if (strcmp(def->defname, OPT_DBLINK) == 0)
{
char *val = strVal(def->arg);
if (strchr(val, '"') != NULL)
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_ATTRIBUTE_VALUE),
errmsg("invalid value for option \"%s\"", def->defname),
errhint("Double quotes are not allowed in the dblink name.")));
}
/* check valid values for "schema" */
if (strcmp(def->defname, OPT_SCHEMA) == 0)
{
char *val = strVal(def->arg);
if (strchr(val, '"') != NULL)
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_ATTRIBUTE_VALUE),
errmsg("invalid value for option \"%s\"", def->defname),
errhint("Double quotes are not allowed in the schema name.")));
}
/* check valid values for max_long */
if (strcmp(def->defname, OPT_MAX_LONG) == 0)
{
char *val = strVal(def->arg);
char *endptr;
unsigned long max_long;
errno = 0;
max_long = strtoul(val, &endptr, 0);
if (val[0] == '\0' || *endptr != '\0' || errno != 0 || max_long < 1 || max_long > 1073741823ul)
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_ATTRIBUTE_VALUE),
errmsg("invalid value for option \"%s\"", def->defname),
errhint("Valid values in this context are integers between 1 and 1073741823.")));
}
/* check valid values for "sample_percent" */
if (strcmp(def->defname, OPT_SAMPLE) == 0)
{
char *val = strVal(def->arg);
char *endptr;
double sample_percent;
errno = 0;
sample_percent = strtod(val, &endptr);
if (val[0] == '\0' || *endptr != '\0' || errno != 0 || sample_percent < 0.000001 || sample_percent > 100.0)
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_ATTRIBUTE_VALUE),
errmsg("invalid value for option \"%s\"", def->defname),
errhint("Valid values in this context are numbers between 0.000001 and 100.")));
}
/* check valid values for "prefetch" */
if (strcmp(def->defname, OPT_PREFETCH) == 0)
{
char *val = strVal(def->arg);
char *endptr;
long prefetch;
errno = 0;
prefetch = strtol(val, &endptr, 0);
if (val[0] == '\0' || *endptr != '\0' || errno != 0 || prefetch < 1 || prefetch > 1000 )
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_ATTRIBUTE_VALUE),
errmsg("invalid value for option \"%s\"", def->defname),
errhint("Valid values in this context are integers between 0 and 1000.")));
}
/* check valid values for "lob_prefetch" */
if (strcmp(def->defname, OPT_LOB_PREFETCH) == 0)
{
char *val = strVal(def->arg);
char *endptr;
long lob_prefetch;
errno = 0;
lob_prefetch = strtol(val, &endptr, 0);
if (val[0] == '\0' || *endptr != '\0' || errno != 0 || lob_prefetch < 0 || lob_prefetch > 536870912 )
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_ATTRIBUTE_VALUE),
errmsg("invalid value for option \"%s\"", def->defname),
errhint("Valid values in this context are integers between 0 and 536870912.")));
}
}
/* check that all required options have been given */
for (i=0; i<option_count; ++i)
{
if (catalog == valid_options[i].optcontext && valid_options[i].optrequired && !option_given[i])
{
ereport(ERROR,
(errcode(ERRCODE_FDW_OPTION_NAME_NOT_FOUND),
errmsg("missing required option \"%s\"", valid_options[i].optname)));
}
}
PG_RETURN_VOID();
}
/*
* oracle_close_connections
* Close all open Oracle connections.
*/
PGDLLEXPORT Datum
oracle_close_connections(PG_FUNCTION_ARGS)
{
if (dml_in_transaction)
ereport(ERROR,
(errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
errmsg("connections with an active transaction cannot be closed"),
errhint("The transaction that modified Oracle data must be closed first.")));
elog(DEBUG1, "oracle_fdw: close all Oracle connections");
oracleCloseConnections();
PG_RETURN_VOID();
}
/*
* oracle_diag
* Get the Oracle client version.
* If a non-NULL argument is supplied, it must be a foreign server name.
* In this case, the remote server version is returned as well.
*/
PGDLLEXPORT Datum
oracle_diag(PG_FUNCTION_ARGS)
{
char *pgversion;
int major, minor, update, patch, port_patch;
StringInfoData version;
/*
* Get the PostgreSQL server version.
* We cannot use PG_VERSION because that would give the version against which
* oracle_fdw was compiled, not the version it is running with.
*/
pgversion = GetConfigOptionByName("server_version", NULL);
/* get the Oracle client version */
oracleClientVersion(&major, &minor, &update, &patch, &port_patch);
initStringInfo(&version);
appendStringInfo(&version, "oracle_fdw %s, PostgreSQL %s, Oracle client %d.%d.%d.%d.%d",
ORACLE_FDW_VERSION,
pgversion,
major, minor, update, patch, port_patch);
if (PG_ARGISNULL(0))
{
/* display some important Oracle environment variables */
static const char * const oracle_env[] = {
"ORACLE_HOME",
"ORACLE_SID",
"TNS_ADMIN",
"TWO_TASK",
"LDAP_ADMIN",
NULL
};
int i;
for (i=0; oracle_env[i] != NULL; ++i)
{
char *val = getenv(oracle_env[i]);
if (val != NULL)
appendStringInfo(&version, ", %s=%s", oracle_env[i], val);
}
}
else
{
oracleSession *session;
Name srvname = PG_GETARG_NAME(0);
session = oracleConnectServer(srvname);
/* get the server version */
oracleServerVersion(session, &major, &minor, &update, &patch, &port_patch);
appendStringInfo(&version, ", Oracle server %d.%d.%d.%d.%d",
major, minor, update, patch, port_patch);
/* free the session (connection will be cached) */
pfree(session);
}
PG_RETURN_TEXT_P(cstring_to_text(version.data));
}
/*
* oracle_execute
* Execute a statement that returns no result values on a foreign server.
*/
PGDLLEXPORT Datum
oracle_execute(PG_FUNCTION_ARGS)
{
Name srvname = PG_GETARG_NAME(0);
char *stmt = text_to_cstring(PG_GETARG_TEXT_PP(1));
oracleSession *session = oracleConnectServer(srvname);
oracleExecuteCall(session, stmt);
/* free the session (connection will be cached) */
pfree(session);
PG_RETURN_VOID();
}
/*
* _PG_init
* Library load-time initalization.
* Sets exitHook() callback for backend shutdown.
*/
void
_PG_init(void)
{
/* check for incompatible server versions */
char *pgver_str = GetConfigOptionByName("server_version_num", NULL);
long pgver = strtol(pgver_str, NULL, 10);
pfree(pgver_str);
if ((pgver >= 90600 && pgver <= 90608)
|| (pgver >= 100000 && pgver <= 100003))
ereport(ERROR,
(errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION),
errmsg("PostgreSQL version \"%s\" not supported by oracle_fdw",
GetConfigOptionByName("server_version", NULL)),
errhint("You'll have to update PostgreSQL to a later minor release.")));
/* register an exit hook */
on_proc_exit(&exitHook, PointerGetDatum(NULL));
}
/*
* oracleGetForeignRelSize
* Get an OracleFdwState for this foreign scan.
* Construct the remote SQL query.
* Provide estimates for the number of tuples, the average width and the cost.
*/
void
oracleGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
{
struct OracleFdwState *fdwState;
int i, major, minor, update, patch, port_patch;
double ntuples = -1;
bool order_by_local;
RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
Oid check_user;
/*
* Get the user whose user mapping should be used (if invalid, the current
* user is used).
*/
#if PG_VERSION_NUM < 160000
check_user = rte->checkAsUser;
#else
check_user = getRTEPermissionInfo(root->parse->rteperminfos, rte)->checkAsUser;
#endif /* PG_VERSION_NUM < 160000 */
elog(DEBUG1, "oracle_fdw: plan foreign table scan");
/*
* Get connection options, connect and get the remote table description.
* To match what ExecCheckRTEPerms does, pass the user whose user mapping
* should be used (if invalid, the current user is used).
*/
fdwState = getFdwState(foreigntableid, NULL, check_user);
/*
* Store the table OID in each table column.
* This is redundant for base relations, but join relations will
* have columns from different tables, and we have to keep track of them.
*/
for (i=0; i<fdwState->oraTable->ncols; ++i){
fdwState->oraTable->cols[i]->varno = baserel->relid;
}
/*
* Classify conditions into remote_conds or local_conds.
* These parameters are used in foreign_join_ok and oracleGetForeignPlan.
* Those conditions that can be pushed down will be collected into
* an Oracle WHERE clause.
*/
fdwState->where_clause = deparseWhereConditions(
fdwState,
baserel,
&(fdwState->local_conds),
&(fdwState->remote_conds)
);
/*
* Determine whether we can potentially push query pathkeys to the remote
* side, avoiding a local sort.
*/
order_by_local = !pushdownOrderBy(root, baserel, fdwState);
/* try to push down LIMIT from Oracle 12.2 on */
oracleServerVersion(fdwState->session, &major, &minor, &update, &patch, &port_patch);
if (major > 12 || (major == 12 && minor > 1))
{
/* but not if ORDER BY cannot be pushed down */
if (!order_by_local &&
((list_length(root->canon_pathkeys) <= 1 && !root->cte_plan_ids)
|| (list_length(root->parse->rtable) == 1)))
{
fdwState->limit_clause = deparseLimit(root, fdwState, baserel);
}
}
/* release Oracle session (will be cached) */
pfree(fdwState->session);
fdwState->session = NULL;
/* use a random "high" value for cost */
fdwState->startup_cost = 10000.0;
/* if baserel->pages > 0, there was an ANALYZE; use the row count estimate */
#if PG_VERSION_NUM < 140000
/* before v14, baserel->tuples == 0 for tables that have never been vacuumed */
if (baserel->pages > 0)
#endif /* PG_VERSION_NUM */
ntuples = baserel->tuples;
/* estimale selectivity locally for all conditions */
/* apply statistics only if we have a reasonable row count estimate */
if (ntuples != -1)
{
/* estimate how conditions will influence the row count */
ntuples = ntuples * clauselist_selectivity(root, baserel->baserestrictinfo, 0, JOIN_INNER, NULL, false);
/* make sure that the estimate is not less that 1 */
ntuples = clamp_row_est(ntuples);
baserel->rows = ntuples;
}
/* estimate total cost as startup cost + 10 * (returned rows) */
fdwState->total_cost = fdwState->startup_cost + baserel->rows * 10.0;
/* store the state so that the other planning functions can use it */
baserel->fdw_private = (void *)fdwState;
}
/* oracleGetForeignPaths
* Create a ForeignPath node and add it as only possible path.
*/
void
oracleGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
{
struct OracleFdwState *fdwState = (struct OracleFdwState *)baserel->fdw_private;
/* add the only path */
add_path(baserel,
(Path *)create_foreignscan_path(
root,
baserel,
#if PG_VERSION_NUM >= 90600
NULL, /* default pathtarget */
#endif /* PG_VERSION_NUM */
baserel->rows,
fdwState->startup_cost,
fdwState->total_cost,
fdwState->usable_pathkeys,
baserel->lateral_relids,
#if PG_VERSION_NUM >= 90500
NULL, /* no extra plan */
#endif /* PG_VERSION_NUM */
#if PG_VERSION_NUM >= 170000
NIL, /* no fdw_restrictinfo */
#endif /* PG_VERSION_NUM */
NIL
)
);
}
#ifdef JOIN_API
/*
* oracleGetForeignJoinPaths
* Add possible ForeignPath to joinrel if the join is safe to push down.
* For now, we can only push down 2-way joins for SELECT.
*/
static void
oracleGetForeignJoinPaths(PlannerInfo *root,
RelOptInfo *joinrel,
RelOptInfo *outerrel,
RelOptInfo *innerrel,
JoinType jointype,
JoinPathExtraData *extra)
{
struct OracleFdwState *fdwState;
ForeignPath *joinpath;
double joinclauses_selectivity;
double rows; /* estimated number of returned rows */
Cost startup_cost;
Cost total_cost;
/*
* Currently we don't push-down joins in query for UPDATE/DELETE.
* This would require a path for EvalPlanQual.
* This restriction might be relaxed in a later release.
*/
if (root->parse->commandType != CMD_SELECT)
{
elog(DEBUG2, "oracle_fdw: don't push down join because it is no SELECT");
return;
}
if (root->rowMarks)
{
elog(DEBUG2, "oracle_fdw: don't push down join with FOR UPDATE");
return;
}
/*
* N-way join is not supported, due to the column definition infrastracture.
* If we can track relid mapping of join relations, we can support N-way join.
*/
if (! IS_SIMPLE_REL(outerrel) || ! IS_SIMPLE_REL(innerrel))
return;
/* skip if this join combination has been considered already */
if (joinrel->fdw_private)
return;
/*
* Create unfinished OracleFdwState which is used to indicate
* that the join relation has already been considered, so that we won't waste
* time considering it again and don't add the same path a second time.
* Once we know that this join can be pushed down, we fill the data structure.
*/
fdwState = (struct OracleFdwState *) palloc0(sizeof(struct OracleFdwState));
joinrel->fdw_private = fdwState;
/* this performs further checks */
if (!foreign_join_ok(root, joinrel, jointype, outerrel, innerrel, extra))
return;
/* estimate the number of result rows for the join */
#if PG_VERSION_NUM < 140000
if (outerrel->pages > 0 && innerrel->pages > 0)
#else
if (outerrel->tuples >= 0 && innerrel->tuples >= 0)
#endif /* PG_VERSION_NUM */
{
/* both relations have been ANALYZEd, so there should be useful statistics */
joinclauses_selectivity = clauselist_selectivity(root, fdwState->joinclauses, 0, JOIN_INNER, extra->sjinfo, false);
rows = clamp_row_est(innerrel->tuples * outerrel->tuples * joinclauses_selectivity);
}
else