forked from laurenz/oracle_fdw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
oracle_fdw.c
4536 lines (4017 loc) · 134 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"
#if PG_VERSION_NUM < 90300
#include "access/htup.h"
#else
#include "access/htup_details.h"
#endif /* PG_VERSION_NUM */
#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_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/explain.h"
#include "commands/vacuum.h"
#include "foreign/fdwapi.h"
#include "foreign/foreign.h"
#include "libpq/md5.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"
#include "optimizer/pathnode.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "parser/parse_relation.h"
#include "parser/parsetree.h"
#include "port.h"
#include "storage/ipc.h"
#include "storage/lock.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/elog.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/resowner.h"
#include "utils/tqual.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/timestamp.h"
#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 < 90200
#define OLD_FDW_API
#else
#undef OLD_FDW_API
#endif /* PG_VERSION_NUM */
#if PG_VERSION_NUM >= 90300
#define WRITE_API
#else
#undef WRITE_API
#endif /* PG_VERSION_NUM */
PG_MODULE_MAGIC;
/*
* 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_USER "user"
#define OPT_PASSWORD "password"
#define OPT_SCHEMA "schema"
#define OPT_TABLE "table"
#define OPT_PLAN_COSTS "plan_costs"
#define OPT_MAX_LONG "max_long"
#define OPT_READONLY "readonly"
#define OPT_KEY "key"
#define DEFAULT_MAX_LONG 32767
/*
* Valid options for oracle_fdw.
*/
static struct OracleFdwOption valid_options[] = {
{OPT_NLS_LANG, ForeignDataWrapperRelationId, false},
{OPT_DBSERVER, ForeignServerRelationId, true},
{OPT_USER, UserMappingRelationId, true},
{OPT_PASSWORD, UserMappingRelationId, true},
{OPT_SCHEMA, ForeignTableRelationId, false},
{OPT_TABLE, ForeignTableRelationId, true},
{OPT_PLAN_COSTS, ForeignTableRelationId, false},
{OPT_MAX_LONG, ForeignTableRelationId, false},
{OPT_READONLY, ForeignTableRelationId, false}
#ifndef OLD_FDW_API
,{OPT_KEY, AttributeRelationId, false}
#endif /* OLD_FDW_API */
};
#define option_count (sizeof(valid_options)/sizeof(struct OracleFdwOption))
#ifdef WRITE_API
/*
* 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;
#endif /* WRITE_API */
/*
* 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 */
char *user; /* Oracle username */
char *password; /* Oracle password */
char *nls_lang; /* Oracle locale information */
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 */
bool *pushdown_clauses; /* array, true if the corresponding clause can be pushed down */
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 */
};
/*
* 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);
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);
/*
* on-load initializer
*/
extern PGDLLEXPORT void _PG_init(void);
/*
* FDW callback routines
*/
#ifdef OLD_FDW_API
static FdwPlan *oraclePlanForeignScan(Oid foreigntableid, PlannerInfo *root, RelOptInfo *baserel);
#else
static void oracleGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid);
static void oracleGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid);
static ForeignScan *oracleGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid, ForeignPath *best_path, List *tlist, List *scan_clauses);
static bool oracleAnalyzeForeignTable(Relation relation, AcquireSampleRowsFunc *func, BlockNumber *totalpages);
#endif /* OLD_FDW_API */
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);
#ifdef WRITE_API
static void oracleAddForeignUpdateTargets(Query *parsetree, RangeTblEntry *target_rte, Relation target_relation);
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);
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);
#endif /* WRITE_API */
/*
* Helper functions
*/
static struct OracleFdwState *getFdwState(Oid foreigntableid, bool *plan_costs);
static void oracleGetOptions(Oid foreigntableid, List **options);
static char *createQuery(oracleSession *session, RelOptInfo *foreignrel, bool modify, struct oraTable *oraTable, List **params, bool **pushdown_clauses);
static void getColumnData(Oid foreigntableid, struct oraTable *oraTable);
#ifndef OLD_FDW_API
static int acquireSampleRowsFunc (Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows);
#endif /* OLD_FDW_API */
static char *getOracleWhereClause(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);
static void checkDataType(oraType oratype, int scale, Oid pgtype, const char *tablename, const char *colname);
static char *guessNlsLang(char *nls_lang);
static List *serializePlanData(struct OracleFdwState *fdwState);
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);
#ifdef WRITE_API
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);
#endif /* WRITE_API */
static void transactionCallback(XactEvent event, void *arg);
static void exitHook(int code, Datum arg);
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);
/*
* 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);
#ifdef OLD_FDW_API
fdwroutine->PlanForeignScan = oraclePlanForeignScan;
#else
fdwroutine->GetForeignRelSize = oracleGetForeignRelSize;
fdwroutine->GetForeignPaths = oracleGetForeignPaths;
fdwroutine->GetForeignPlan = oracleGetForeignPlan;
fdwroutine->AnalyzeForeignTable = oracleAnalyzeForeignTable;
#endif /* OLD_FDW_API */
fdwroutine->ExplainForeignScan = oracleExplainForeignScan;
fdwroutine->BeginForeignScan = oracleBeginForeignScan;
fdwroutine->IterateForeignScan = oracleIterateForeignScan;
fdwroutine->ReScanForeignScan = oracleReScanForeignScan;
fdwroutine->EndForeignScan = oracleEndForeignScan;
#ifdef WRITE_API
fdwroutine->AddForeignUpdateTargets = oracleAddForeignUpdateTargets;
fdwroutine->PlanForeignModify = oraclePlanForeignModify;
fdwroutine->BeginForeignModify = oracleBeginForeignModify;
fdwroutine->ExecForeignInsert = oracleExecForeignInsert;
fdwroutine->ExecForeignUpdate = oracleExecForeignUpdate;
fdwroutine->ExecForeignDelete = oracleExecForeignDelete;
fdwroutine->EndForeignModify = oracleEndForeignModify;
fdwroutine->ExplainForeignModify = oracleExplainForeignModify;
fdwroutine->IsForeignRelUpdatable = oracleIsForeignRelUpdatable;
#endif /* WRITE_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 plan_costs */
if (strcmp(def->defname, OPT_PLAN_COSTS) == 0
|| strcmp(def->defname, OPT_READONLY) == 0
#ifndef OLD_FDW_API
|| strcmp(def->defname, OPT_KEY) == 0
#endif /* OLD_FDW_API */
)
{
char *val = ((Value *)(def->arg))->val.str;
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 "table" and "schema" */
if (strcmp(def->defname, OPT_TABLE) == 0
|| strcmp(def->defname, OPT_SCHEMA) == 0)
{
char *val = ((Value *)(def->arg))->val.str;
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 names.")));
}
/* check valid values for max_long */
if (strcmp(def->defname, OPT_MAX_LONG) == 0)
{
char *val = ((Value *) (def->arg))->val.str;
char *endptr;
unsigned long max_long = strtoul(val, &endptr, 0);
if (val[0] == '\0' || *endptr != '\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 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)
{
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)
{
Oid srvId = InvalidOid;
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
{
/* get the server version only if a non-null argument was given */
HeapTuple tup;
Relation rel;
Name srvname = PG_GETARG_NAME(0);
ForeignServer *server;
UserMapping *mapping;
ForeignDataWrapper *wrapper;
List *options;
ListCell *cell;
char *nls_lang = NULL, *user = NULL, *password = NULL, *dbserver = NULL;
oracleSession *session;
/* look up foreign server with this name */
rel = heap_open(ForeignServerRelationId, AccessShareLock);
tup = SearchSysCacheCopy1(FOREIGNSERVERNAME, NameGetDatum(srvname));
if (!HeapTupleIsValid(tup))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("server \"%s\" does not exist", NameStr(*srvname))));
srvId = HeapTupleGetOid(tup);
heap_close(rel, AccessShareLock);
/* get the foreign server, the user mapping and the FDW */
server = GetForeignServer(srvId);
mapping = GetUserMapping(GetUserId(), srvId);
wrapper = GetForeignDataWrapper(server->fdwid);
/* get all options for these objects */
options = wrapper->options;
options = list_concat(options, server->options);
options = list_concat(options, mapping->options);
foreach(cell, options)
{
DefElem *def = (DefElem *) lfirst(cell);
if (strcmp(def->defname, OPT_NLS_LANG) == 0)
nls_lang = ((Value *) (def->arg))->val.str;
if (strcmp(def->defname, OPT_DBSERVER) == 0)
dbserver = ((Value *) (def->arg))->val.str;
if (strcmp(def->defname, OPT_USER) == 0)
user = ((Value *) (def->arg))->val.str;
if (strcmp(def->defname, OPT_PASSWORD) == 0)
password = ((Value *) (def->arg))->val.str;
}
/* guess a good NLS_LANG environment setting */
nls_lang = guessNlsLang(nls_lang);
/* connect to Oracle database */
session = oracleGetSession(
dbserver,
user,
password,
nls_lang,
NULL,
1
);
/* 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));
}
/*
* _PG_init
* Library load-time initalization, sets exitHook() callback for
* backend shutdown.
*/
void
_PG_init(void)
{
on_proc_exit(&exitHook, PointerGetDatum(NULL));
}
#ifdef OLD_FDW_API
/*
* oraclePlanForeignScan
* Get an OracleFdwState for this foreign scan.
* A FdwPlan is created and the state is are stored
* ("serialized") in its fdw_private field.
*/
FdwPlan *
oraclePlanForeignScan(Oid foreigntableid,
PlannerInfo *root,
RelOptInfo *baserel)
{
struct OracleFdwState *fdwState;
FdwPlan *fdwplan;
List *fdw_private;
bool plan_costs;
int i;
elog(DEBUG1, "oracle_fdw: plan foreign table scan on %d", foreigntableid);
/* get connection options, connect and get the remote table description */
fdwState = getFdwState(foreigntableid, &plan_costs);
/* construct Oracle query and get the list of parameters and actions for RestrictInfos */
fdwState->query = createQuery(fdwState->session, baserel, false, fdwState->oraTable, &(fdwState->params), &(fdwState->pushdown_clauses));
elog(DEBUG1, "oracle_fdw: remote query is: %s", fdwState->query);
/* get PostgreSQL column data types, check that they match Oracle's */
for (i=0; i<fdwState->oraTable->ncols; ++i)
if (fdwState->oraTable->cols[i]->used)
checkDataType(
fdwState->oraTable->cols[i]->oratype,
fdwState->oraTable->cols[i]->scale,
fdwState->oraTable->cols[i]->pgtype,
fdwState->oraTable->pgname,
fdwState->oraTable->cols[i]->pgname
);
/* get Oracle's (bad) estimate only if plan_costs is set */
if (plan_costs)
{
/* get Oracle's cost estimates for the query */
oracleEstimate(fdwState->session, fdwState->query, seq_page_cost, BLCKSZ, &(fdwState->startup_cost), &(fdwState->total_cost), &baserel->rows, &baserel->width);
}
else
{
/* otherwise, use a random "high" value */
fdwState->startup_cost = fdwState->total_cost = 10000.0;
}
/* release Oracle session (will be cached) */
pfree(fdwState->session);
fdwState->session = NULL;
/* "serialize" all necessary information in the private area */
fdw_private = serializePlanData(fdwState);
/* construct FdwPlan */
fdwplan = makeNode(FdwPlan);
fdwplan->startup_cost = fdwState->startup_cost;
fdwplan->total_cost = fdwState->total_cost;
fdwplan->fdw_private = fdw_private;
return fdwplan;
}
#else
/*
* 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;
bool plan_costs, need_keys = false, for_update = false, has_trigger;
List *local_conditions = NIL;
int i;
double ntuples = -1;
Relation rel;
elog(DEBUG1, "oracle_fdw: plan foreign table scan on %d", foreigntableid);
/* check if the foreign scan is for an UPDATE or DELETE */
if (baserel->relid == root->parse->resultRelation &&
(root->parse->commandType == CMD_UPDATE ||
root->parse->commandType == CMD_DELETE))
{
/* we need the table's primary key columns */
need_keys = true;
}
/* check if FOR [KEY] SHARE/UPDATE was specified */
if (need_keys || get_parse_rowmark(root->parse, baserel->relid))
{
/* we should add FOR UPDATE */
for_update = true;
}
/* get connection options, connect and get the remote table description */
fdwState = getFdwState(foreigntableid, &plan_costs);
if (need_keys)
{
/* we need to fetch all primary key columns */
for (i=0; i<fdwState->oraTable->ncols; ++i)
if (fdwState->oraTable->cols[i]->pkey)
fdwState->oraTable->cols[i]->used = 1;
}
/*
* Core code already has some lock on each rel being planned, so we can
* use NoLock here.
*/
rel = heap_open(foreigntableid, NoLock);
/* is there an AFTER trigger FOR EACH ROW? */
has_trigger = (baserel->relid == root->parse->resultRelation) && rel->trigdesc
&& ((root->parse->commandType == CMD_UPDATE && rel->trigdesc->trig_update_after_row)
|| (root->parse->commandType == CMD_DELETE && rel->trigdesc->trig_delete_after_row));
heap_close(rel, NoLock);
if (has_trigger)
{
/* we need to fetch and return all columns */
for (i=0; i<fdwState->oraTable->ncols; ++i)
if (fdwState->oraTable->cols[i]->pgname)
fdwState->oraTable->cols[i]->used = 1;
}
/* construct Oracle query and get the list of parameters and actions for RestrictInfos */
fdwState->query = createQuery(fdwState->session, baserel, for_update, fdwState->oraTable, &(fdwState->params), &(fdwState->pushdown_clauses));
elog(DEBUG1, "oracle_fdw: remote query is: %s", fdwState->query);
/* get PostgreSQL column data types, check that they match Oracle's */
for (i=0; i<fdwState->oraTable->ncols; ++i)
if (fdwState->oraTable->cols[i]->used)
checkDataType(
fdwState->oraTable->cols[i]->oratype,
fdwState->oraTable->cols[i]->scale,
fdwState->oraTable->cols[i]->pgtype,
fdwState->oraTable->pgname,
fdwState->oraTable->cols[i]->pgname
);
/* get Oracle's (bad) estimate only if plan_costs is set */
if (plan_costs)
{
/* get Oracle's cost estimates for the query */
oracleEstimate(fdwState->session, fdwState->query, seq_page_cost, BLCKSZ, &(fdwState->startup_cost), &(fdwState->total_cost), &ntuples, &baserel->width);
/* estimate selectivity only for conditions that are not pushed down */
for (i=list_length(baserel->baserestrictinfo)-1; i>=0; --i)
if (! fdwState->pushdown_clauses[i])
local_conditions = lcons(list_nth(baserel->baserestrictinfo, i), local_conditions);
}
else
{
/* otherwise, use a random "high" value for cost */
fdwState->startup_cost = fdwState->total_cost = 10000.0;
/* if baserel->pages > 0, there was an ANALYZE; use the row count estimate */
if (baserel->pages > 0)
ntuples = baserel->tuples;
/* estimale selectivity locally for all conditions */
local_conditions = baserel->baserestrictinfo;
}
/* release Oracle session (will be cached) */
pfree(fdwState->session);
fdwState->session = NULL;
/* apply statistics only if we have a reasonable row count estimate */
if (ntuples != -1)
{
/* estimate how clauses that are not pushed down will influence row count */
ntuples = ntuples * clauselist_selectivity(root, local_conditions, 0, JOIN_INNER, NULL);
/* make sure that the estimate is not less that 1 */
ntuples = clamp_row_est(ntuples);
baserel->rows = ntuples;
}
/* 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_path(baserel,
(Path *)create_foreignscan_path(root, baserel, baserel->rows,
fdwState->startup_cost, fdwState->total_cost,
NIL, NULL, NIL));
}
/*
* oracleGetForeignPlan
* Construct a ForeignScan node containing the serialized OracleFdwState,
* the RestrictInfo clauses not handled entirely by Oracle and the list
* of parameters we need for execution.
*/
ForeignScan
*oracleGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid, ForeignPath *best_path, List *tlist, List *scan_clauses)
{
struct OracleFdwState *fdwState = (struct OracleFdwState *)baserel->fdw_private;
List *fdw_private, *keep_clauses = NIL;
ListCell *cell1, *cell2;
int i;
/* "serialize" all necessary information for the path private area */
fdw_private = serializePlanData(fdwState);
/* keep only those clauses that are not handled by Oracle */
foreach(cell1, scan_clauses)
{
i = 0;
foreach(cell2, baserel->baserestrictinfo)
{
if (equal(lfirst(cell1), lfirst(cell2)) && ! fdwState->pushdown_clauses[i])
{
keep_clauses = lcons(lfirst(cell1), keep_clauses);
break;
}
++i;
}
}
/* remove the RestrictInfo node from all remaining clauses */
keep_clauses = extract_actual_clauses(keep_clauses, false);
/* Create the ForeignScan node */
return make_foreignscan(tlist, keep_clauses, baserel->relid, fdwState->params, fdw_private);
}
bool
oracleAnalyzeForeignTable(Relation relation, AcquireSampleRowsFunc *func, BlockNumber *totalpages)
{
*func = acquireSampleRowsFunc;
/* use positive page count as a sign that the table has been ANALYZEd */
*totalpages = 42;
return true;
}
#endif /* OLD_FDW_API */
/*
* oracleExplainForeignScan
* Produce extra output for EXPLAIN:
* the Oracle query and, if VERBOSE was given, the execution plan.
*/
void
oracleExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
struct OracleFdwState *fdw_state = (struct OracleFdwState *)node->fdw_state;
char **plan;
int nrows, i;
elog(DEBUG1, "oracle_fdw: explain foreign table scan on %d", RelationGetRelid(node->ss.ss_currentRelation));
/* show query */
ExplainPropertyText("Oracle query", fdw_state->query, es);
if (es->verbose)
{
/* get the EXPLAIN PLAN */
oracleExplain(fdw_state->session, fdw_state->query, &nrows, &plan);
/* add it to explain text */
for (i=0; i<nrows; ++i)
{
ExplainPropertyText("Oracle plan", plan[i], es);
}
}
}
/*
* oracleBeginForeignScan
* Recover ("deserialize") connection information, remote query,
* Oracle table description and parameter list from the plan's
* "fdw_private" field.
* Reestablish a connection to Oracle.
*/
void
oracleBeginForeignScan(ForeignScanState *node, int eflags)
{
ForeignScan *fsplan = (ForeignScan *)node->ss.ps.plan;
#ifdef OLD_FDW_API
List *fdw_private = ((FdwPlan *)fsplan->fdwplan)->fdw_private;
#else
List *fdw_private = fsplan->fdw_private;
List *exec_exprs;
ListCell *cell;
int index;
#endif /* OLD_FDW_API */
struct paramDesc *paramDesc;
struct OracleFdwState *fdw_state;
/* deserialize private plan data */
fdw_state = deserializePlanData(fdw_private);
node->fdw_state = (void *)fdw_state;
#ifndef OLD_FDW_API
/* create an ExprState tree for the parameter expressions */
exec_exprs = (List *)ExecInitExpr((Expr *)fsplan->fdw_exprs, (PlanState *)node);
/* create the list of parameters */
index = 0;
foreach(cell, exec_exprs)
{
ExprState *expr = (ExprState *)lfirst(cell);
char parname[10];
/* count, but skip deleted entries */
++index;
if (expr == NULL)
continue;
/* create a new entry in the parameter list */
paramDesc = (struct paramDesc *)palloc(sizeof(struct paramDesc));
snprintf(parname, 10, ":p%d", index);
paramDesc->name = pstrdup(parname);
paramDesc->type = exprType((Node *)(expr->expr));
if (paramDesc->type == TEXTOID || paramDesc->type == VARCHAROID
|| paramDesc->type == BPCHAROID || paramDesc->type == CHAROID)
paramDesc->bindType = BIND_STRING;
else if (paramDesc->type == DATEOID || paramDesc->type == TIMESTAMPOID
|| paramDesc->type == TIMESTAMPTZOID)
paramDesc->bindType = BIND_TIMESTAMP;
else
paramDesc->bindType = BIND_NUMBER;
paramDesc->value = NULL;
paramDesc->node = expr;
paramDesc->bindh = NULL;
paramDesc->colnum = -1;
paramDesc->next = fdw_state->paramList;
fdw_state->paramList = paramDesc;
}
#endif /* OLD_FDW_API */
/* add a fake parameter ":now" if that string appears in the query */
if (strstr(fdw_state->query, ":now") != NULL)
{
paramDesc = (struct paramDesc *)palloc(sizeof(struct paramDesc));
paramDesc->name = pstrdup(":now");
paramDesc->type = TIMESTAMPTZOID;
paramDesc->bindType = BIND_TIMESTAMP;
paramDesc->value = NULL;
paramDesc->node = NULL;
paramDesc->bindh = NULL;
paramDesc->colnum = -1;
paramDesc->next = fdw_state->paramList;
fdw_state->paramList = paramDesc;
}
elog(DEBUG1, "oracle_fdw: begin foreign table scan on %d", RelationGetRelid(node->ss.ss_currentRelation));
/* connect to Oracle database */
fdw_state->session = oracleGetSession(
fdw_state->dbserver,
fdw_state->user,
fdw_state->password,
fdw_state->nls_lang,
fdw_state->oraTable->pgname,
#ifdef WRITE_API
GetCurrentTransactionNestLevel()
#else
1
#endif /* WRITE_API */
);
/* initialize row count to zero */
fdw_state->rowcount = 0;
}
/*
* oracleIterateForeignScan
* On first invocation (if there is no Oracle statement yet),
* get the actual parameter values and run the remote query against
* the Oracle database, retrieving the first result row.
* Subsequent invocations will fetch more result rows until there
* are no more.
* The result is stored as a virtual tuple in the ScanState's
* TupleSlot and returned.
*/
TupleTableSlot *
oracleIterateForeignScan(ForeignScanState *node)
{
TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
ExprContext *econtext = node->ss.ps.ps_ExprContext;
int have_result;
struct OracleFdwState *fdw_state = (struct OracleFdwState *)node->fdw_state;
if (oracleIsStatementOpen(fdw_state->session))
{
elog(DEBUG3, "oracle_fdw: get next row in foreign table scan on %d", RelationGetRelid(node->ss.ss_currentRelation));
/* fetch the next result row */
have_result = oracleFetchNext(fdw_state->session);
}
else
{
/* fill the parameter list with the actual values */
char *paramInfo = setSelectParameters(fdw_state->paramList, econtext);
/* execute the Oracle statement and fetch the first row */
elog(DEBUG1, "oracle_fdw: execute query in foreign table scan on %d%s", RelationGetRelid(node->ss.ss_currentRelation), paramInfo);
oraclePrepareQuery(fdw_state->session, fdw_state->query, fdw_state->oraTable);
have_result = oracleExecuteQuery(fdw_state->session, fdw_state->oraTable, fdw_state->paramList);
}
/* initialize virtual tuple */
ExecClearTuple(slot);
if (have_result)
{
/* increase row count */
++fdw_state->rowcount;
/* convert result to arrays of values and null indicators */
convertTuple(fdw_state, slot->tts_values, slot->tts_isnull, false);
/* store the virtual tuple */
ExecStoreVirtualTuple(slot);
}
else
{
/* close the statement */
oracleCloseStatement(fdw_state->session);
}
return slot;
}
/*
* oracleEndForeignScan
* Close the currently active Oracle statement.
*/
void
oracleEndForeignScan(ForeignScanState *node)
{
struct OracleFdwState *fdw_state = (struct OracleFdwState *)node->fdw_state;
elog(DEBUG1, "oracle_fdw: end foreign table scan on %d", RelationGetRelid(node->ss.ss_currentRelation));
/* release the Oracle session */