-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathjdbc_fdw.c
1188 lines (1020 loc) · 28.3 KB
/
jdbc_fdw.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* foreign-data wrapper for JDBC
*
* Copyright (c) 2012, PostgreSQL Global Development Group
*
* This software is released under the PostgreSQL Licence
*
* Author: Atri Sharma <[email protected]>
*
* IDENTIFICATION
* jdbc_fdw/jdbc_fdw.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <libpq/pqsignal.h>
#include "funcapi.h"
#include "access/reloptions.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_user_mapping.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "foreign/fdwapi.h"
#include "foreign/foreign.h"
#include "miscadmin.h"
#include "mb/pg_wchar.h"
#include "optimizer/cost.h"
#include "storage/fd.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/rel.h"
#include "storage/ipc.h"
#if (PG_VERSION_NUM >= 90200)
#include "optimizer/pathnode.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/planmain.h"
#endif
#include "jni.h"
#define Str(arg) #arg
#define StrValue(arg) Str(arg)
#define STR_PKGLIBDIR StrValue(PKG_LIB_DIR)
PG_MODULE_MAGIC;
static JNIEnv *env;
static JavaVM *jvm;
static bool InterruptFlag; /* Used for checking for SIGINT interrupt */
/*
* Describes the valid options for objects that use this wrapper.
*/
struct jdbcFdwOption
{
const char *optname;
Oid optcontext; /* Oid of catalog in which option may appear */
};
/*
* Valid options for jdbc_fdw.
*
*/
static struct jdbcFdwOption valid_options[] =
{
/* Connection options */
{ "drivername", ForeignServerRelationId },
{ "url", ForeignServerRelationId },
{ "querytimeout", ForeignServerRelationId },
{ "jarfile", ForeignServerRelationId },
{ "maxheapsize", ForeignServerRelationId },
{ "username", UserMappingRelationId },
{ "password", UserMappingRelationId },
{ "query", ForeignTableRelationId },
{ "table", ForeignTableRelationId },
/* Sentinel */
{ NULL, InvalidOid }
};
/*
* FDW-specific information for ForeignScanState.fdw_state.
*/
typedef struct jdbcFdwExecutionState
{
char *query;
int NumberOfRows;
jobject java_call;
int NumberOfColumns;
} jdbcFdwExecutionState;
/*
* SQL functions
*/
extern Datum jdbc_fdw_handler(PG_FUNCTION_ARGS);
extern Datum jdbc_fdw_validator(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(jdbc_fdw_handler);
PG_FUNCTION_INFO_V1(jdbc_fdw_validator);
/*
* FDW callback routines
*/
#if (PG_VERSION_NUM < 90200)
static FdwPlan *jdbcPlanForeignScan(Oid foreigntableid,PlannerInfo *root, RelOptInfo *baserel);
#endif
#if (PG_VERSION_NUM >= 90200)
static void jdbcGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid);
static void jdbcGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid);
static ForeignScan *jdbcGetForeignPlan(
PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses
#if PG_VERSION_NUM >= 90500
,
/*
* Require PostgreSQL >= 9.5
*/
Plan *outer_plan
#endif
);
#endif
static void jdbcExplainForeignScan(ForeignScanState *node, ExplainState *es);
static void jdbcBeginForeignScan(ForeignScanState *node, int eflags);
static TupleTableSlot *jdbcIterateForeignScan(ForeignScanState *node);
static void jdbcReScanForeignScan(ForeignScanState *node);
static void jdbcEndForeignScan(ForeignScanState *node);
/*
* Helper functions
*/
static bool jdbcIsValidOption(const char *option, Oid context);
static void jdbcGetOptions(
Oid foreigntableid,
char **drivername,
char **url,
int *querytimeout,
char **jarfile,
int* maxheapsize,
char **username,
char **password,
char **query,
char **table
);
/*
* Uses a String object's content to create an instance of C String
*/
static char* ConvertStringToCString(jobject);
/*
* JVM Initialization function
*/
static void JVMInitialization(Oid);
/*
* JVM destroy function
*/
static void DestroyJVM();
/*
* SIGINT interrupt handler
*/
static void SIGINTInterruptHandler(int);
/*
* SIGINT interrupt check and process function
*/
static void SIGINTInterruptCheckProcess();
/*
* Release all resources used by the execution of an FDW query.
*/
static void releaseJdbcFdwExecutionState(jdbcFdwExecutionState **);
/*
* releaseJdbcFdwExecutionState
* Returns all resources used by festate to the operating system.
*/
static void releaseJdbcFdwExecutionState(jdbcFdwExecutionState **festate)
{
if ((*festate)->query)
{
pfree((*festate)->query);
(*festate)->query = 0;
}
(*env)->DeleteGlobalRef(env, (*festate)->java_call);
(*festate)->java_call = NULL;
pfree(*festate);
(*festate) = NULL;
}
/*
* SIGINTInterruptCheckProcess
* Checks and processes if SIGINT interrupt occurs
*/
static void
SIGINTInterruptCheckProcess(jdbcFdwExecutionState **festate)
{
jclass JDBCUtilsClass;
jmethodID id_cancel;
jstring cancel_result = NULL;
char *cancel_result_cstring = NULL;
if (InterruptFlag == false)
{
return;
}
PG_TRY();
{
if (festate != NULL)
{
JDBCUtilsClass = (*env)->FindClass(env, "JDBCUtils");
if (JDBCUtilsClass == NULL)
{
elog(ERROR, "JDBCUtilsClass is NULL");
}
id_cancel = (*env)->GetMethodID(env, JDBCUtilsClass, "Cancel", "()Ljava/lang/String;");
if (id_cancel == NULL)
{
elog(ERROR, "id_cancel is NULL");
}
cancel_result = (*env)->CallObjectMethod(env,(*festate)->java_call,id_cancel);
if (cancel_result != NULL)
{
cancel_result_cstring = ConvertStringToCString((jobject)cancel_result);
elog(ERROR, "%s", cancel_result_cstring);
}
}
elog(ERROR, "Query has been cancelled");
}
PG_CATCH();
{
InterruptFlag = false;
if (festate != NULL)
{
(*env)->ReleaseStringUTFChars(env, cancel_result, cancel_result_cstring);
(*env)->DeleteLocalRef(env, cancel_result);
releaseJdbcFdwExecutionState(festate);
}
PG_RE_THROW();
}
PG_END_TRY();
}
/*
* ConvertStringToCString
* Uses a String object passed as a jobject to the function to
* create an instance of C String.
*/
static char*
ConvertStringToCString(jobject java_cstring)
{
jclass JavaString;
char *StringPointer;
JavaString = (*env)->FindClass(env, "java/lang/String");
if (!((*env)->IsInstanceOf(env, java_cstring, JavaString)))
{
elog(ERROR, "Object not an instance of String class");
}
if (java_cstring != NULL)
{
StringPointer = (char*)(*env)->GetStringUTFChars(env, (jstring)java_cstring, 0);
}
else
{
StringPointer = NULL;
}
return (StringPointer);
}
/*
* DestroyJVM
* Shuts down the JVM.
*/
static void
DestroyJVM()
{
(*jvm)->DestroyJavaVM(jvm);
}
/*
* JVMInitialization
* Create the JVM which will be used for calling the Java routines
* that use JDBC to connect and access the foreign database.
*
*/
static void
JVMInitialization(Oid foreigntableid)
{
jint res = -5;/* Initializing the value of res so that we can check it later to see whether JVM has been correctly created or not*/
JavaVMInitArgs vm_args;
static bool FunctionCallCheck = false; /* This flag safeguards against multiple calls of JVMInitialization().*/
char strpkglibdir[] = STR_PKGLIBDIR;
char *classpath;
char *svr_drivername = NULL;
char *svr_url = NULL;
char *svr_username = NULL;
char *svr_password = NULL;
char *svr_query = NULL;
char *svr_table = NULL;
char *svr_jarfile = NULL;
char *maxheapsizeoption = NULL;
int svr_querytimeout = 0;
int svr_maxheapsize = 0;
jdbcGetOptions(
foreigntableid,
&svr_drivername,
&svr_url,
&svr_querytimeout,
&svr_jarfile,
&svr_maxheapsize,
&svr_username,
&svr_password,
&svr_query,
&svr_table
);
if (FunctionCallCheck == false)
{
vm_args.version = JNI_VERSION_1_2;
vm_args.ignoreUnrecognized = JNI_FALSE;
vm_args.nOptions = 2;
classpath = (char*)palloc(strlen(strpkglibdir) + 19);
snprintf(classpath, strlen(strpkglibdir) + 19, "-Djava.class.path=%s", strpkglibdir);
if (svr_maxheapsize != 0) /* If the user has given a value for setting the max heap size of the JVM */
{
maxheapsizeoption = (char*)palloc(sizeof(int) + 6);
snprintf(maxheapsizeoption, sizeof(int) + 6, "-Xmx%dm", svr_maxheapsize);
vm_args.nOptions++;
}
vm_args.options = (JavaVMOption*)palloc(sizeof(JavaVMOption)*vm_args.nOptions);
vm_args.options[0].optionString = "-Xrs";
vm_args.options[1].optionString = classpath;
if (maxheapsizeoption != NULL)
{
vm_args.options[2].optionString = maxheapsizeoption;
}
/* Create the Java VM */
res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
if (res < 0)
{
ereport(ERROR,
(errmsg("Failed to create Java VM")
));
}
/* Register an on_proc_exit handler that shuts down the JVM.*/
on_proc_exit(DestroyJVM, 0);
FunctionCallCheck = true;
pfree(vm_args.options);
}
}
/*
* SIGINTInterruptHandler
* Handles SIGINT interrupt
*/
static void
SIGINTInterruptHandler(int sig)
{
InterruptFlag = true;
}
/*
* Foreign-data wrapper handler function: return a struct with pointers
* to my callback routines.
*/
Datum
jdbc_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *fdwroutine = makeNode(FdwRoutine);
#if (PG_VERSION_NUM < 90200)
fdwroutine->PlanForeignScan = jdbcPlanForeignScan;
#endif
#if (PG_VERSION_NUM >= 90200)
fdwroutine->GetForeignRelSize = jdbcGetForeignRelSize;
fdwroutine->GetForeignPaths = jdbcGetForeignPaths;
fdwroutine->GetForeignPlan = jdbcGetForeignPlan;
#endif
fdwroutine->ExplainForeignScan = jdbcExplainForeignScan;
fdwroutine->BeginForeignScan = jdbcBeginForeignScan;
fdwroutine->IterateForeignScan = jdbcIterateForeignScan;
fdwroutine->ReScanForeignScan = jdbcReScanForeignScan;
fdwroutine->EndForeignScan = jdbcEndForeignScan;
pqsignal(SIGINT, SIGINTInterruptHandler);
PG_RETURN_POINTER(fdwroutine);
}
/*
* Validate the generic options given to a FOREIGN DATA WRAPPER, SERVER,
* USER MAPPING or FOREIGN TABLE that uses jdbc_fdw.
*
* Raise an ERROR if the option or its value is considered invalid.
*/
Datum
jdbc_fdw_validator(PG_FUNCTION_ARGS)
{
List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
Oid catalog = PG_GETARG_OID(1);
char *svr_drivername = NULL;
char *svr_url = NULL;
char *svr_username = NULL;
char *svr_password = NULL;
char *svr_query = NULL;
char *svr_table = NULL;
char *svr_jarfile = NULL;
int svr_querytimeout = 0;
int svr_maxheapsize = 0;
ListCell *cell;
/*
* Check that only options supported by jdbc_fdw,
* and allowed for the current object type, are given.
*/
foreach(cell, options_list)
{
DefElem *def = (DefElem *) lfirst(cell);
if (!jdbcIsValidOption(def->defname, catalog))
{
struct jdbcFdwOption *opt;
StringInfoData buf;
/*
* Unknown option specified, complain about it. Provide a hint
* with list of valid options for the object.
*/
initStringInfo(&buf);
for (opt = valid_options; opt->optname; opt++)
{
if (catalog == opt->optcontext)
appendStringInfo(&buf, "%s%s", (buf.len > 0) ? ", " : "",
opt->optname);
}
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
errmsg("invalid option \"%s\"", def->defname),
errhint("Valid options in this context are: %s", buf.len ? buf.data : "<none>")
));
}
if (strcmp(def->defname, "drivername") == 0)
{
if (svr_drivername)
ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: drivername (%s)", defGetString(def))
));
svr_drivername = defGetString(def);
}
if (strcmp(def->defname, "url") == 0)
{
if (svr_url)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: url (%s)", defGetString(def))
));
svr_url = defGetString(def);
}
if (strcmp(def->defname, "querytimeout") == 0)
{
if (svr_querytimeout)
ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: querytimeout (%s)", defGetString(def))
));
svr_querytimeout = atoi(defGetString(def));
}
if (strcmp(def->defname, "jarfile") == 0)
{
if (svr_jarfile)
ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: jarfile (%s)", defGetString(def))
));
svr_jarfile = defGetString(def);
}
if (strcmp(def->defname, "maxheapsize") == 0)
{
if (svr_maxheapsize)
ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: maxheapsize (%s)", defGetString(def))
));
svr_maxheapsize = atoi(defGetString(def));
}
if (strcmp(def->defname, "username") == 0)
{
if (svr_username)
ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: username (%s)", defGetString(def))
));
svr_username = defGetString(def);
}
if (strcmp(def->defname, "password") == 0)
{
if (svr_password)
ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: password (%s)", defGetString(def))
));
svr_password = defGetString(def);
}
else if (strcmp(def->defname, "query") == 0)
{
if (svr_table)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting options: query cannot be used with table")
));
if (svr_query)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: query (%s)", defGetString(def))
));
svr_query = defGetString(def);
}
else if (strcmp(def->defname, "table") == 0)
{
if (svr_query)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting options: table cannot be used with query")
));
if (svr_table)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: table (%s)", defGetString(def))
));
svr_table = defGetString(def);
}
}
if (catalog == ForeignServerRelationId && svr_drivername == NULL)
{
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("Driver name must be specified")
));
}
if (catalog == ForeignServerRelationId && svr_url == NULL)
{
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("URL must be specified")
));
}
if (catalog == ForeignServerRelationId && svr_jarfile == NULL)
{
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("JAR file must be specified")
));
}
if (catalog == ForeignTableRelationId && svr_query == NULL && svr_table == NULL)
{
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("either a table or a query must be specified")
));
}
PG_RETURN_VOID();
}
/*
* Check if the provided option is one of the valid options.
* context is the Oid of the catalog holding the object the option is for.
*/
static bool
jdbcIsValidOption(const char *option, Oid context)
{
struct jdbcFdwOption *opt;
for (opt = valid_options; opt->optname; opt++)
{
if (context == opt->optcontext && strcmp(opt->optname, option) == 0)
return true;
}
return false;
}
/*
* Fetch the options for a jdbc_fdw foreign table.
*/
static void
jdbcGetOptions(Oid foreigntableid, char **drivername, char **url, int *querytimeout, char **jarfile, int *maxheapsize, char **username, char **password, char **query, char **table)
{
ForeignTable *f_table;
ForeignServer *f_server;
UserMapping *f_mapping;
List *options;
ListCell *lc;
/*
* Extract options from FDW objects.
*/
f_table = GetForeignTable(foreigntableid);
f_server = GetForeignServer(f_table->serverid);
f_mapping = GetUserMapping(GetUserId(), f_table->serverid);
options = NIL;
options = list_concat(options, f_table->options);
options = list_concat(options, f_server->options);
options = list_concat(options, f_mapping->options);
/* Loop through the options, and get the server/port */
foreach(lc, options)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, "drivername") == 0)
{
*drivername = defGetString(def);
}
if (strcmp(def->defname, "username") == 0)
{
*username = defGetString(def);
}
if (strcmp(def->defname, "querytimeout") == 0)
{
*querytimeout = atoi(defGetString(def));
}
if (strcmp(def->defname, "jarfile") == 0)
{
*jarfile = defGetString(def);
}
if (strcmp(def->defname, "maxheapsize") == 0)
{
*maxheapsize = atoi(defGetString(def));
}
if (strcmp(def->defname, "password") == 0)
{
*password = defGetString(def);
}
if (strcmp(def->defname, "query") == 0)
{
*query = defGetString(def);
}
if (strcmp(def->defname, "table") == 0)
{
*table = defGetString(def);
}
if (strcmp(def->defname, "url") == 0)
{
*url = defGetString(def);
}
}
}
#if (PG_VERSION_NUM < 90200)
/*
* jdbcPlanForeignScan
* Create a FdwPlan for a scan on the foreign table
*/
static FdwPlan*
jdbcPlanForeignScan(Oid foreigntableid, PlannerInfo *root, RelOptInfo *baserel)
{
FdwPlan *fdwplan = NULL;
char *svr_drivername = NULL;
char *svr_username = NULL;
char *svr_password = NULL;
char *svr_query = NULL;
char *svr_table = NULL;
char *svr_url = NULL;
char *svr_jarfile = NULL;
int svr_querytimeout = 0;
int svr_maxheapsize = 0;
char *query;
SIGINTInterruptCheckProcess(NULL);
fdwplan = makeNode(FdwPlan);
JVMInitialization(foreigntableid);
/* Fetch options */
jdbcGetOptions(
foreigntableid,
&svr_drivername,
&svr_url,
&svr_querytimeout,
&svr_jarfile,
&svr_maxheapsize,
&svr_username,
&svr_password,
&svr_query,
&svr_table
);
/* Build the query */
if (svr_query)
{
size_t len = strlen(svr_query) + 9;
query = (char *) palloc(len);
snprintf(query, len, "EXPLAIN %s", svr_query);
}
else
{
size_t len = strlen(svr_table) + 23;
query = (char *) palloc(len);
snprintf(query, len, "EXPLAIN SELECT * FROM %s", svr_table);
}
return (fdwplan);
}
#endif
/*
* jdbcExplainForeignScan
* Produce extra output for EXPLAIN
*/
static void
jdbcExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
char *svr_drivername = NULL;
char *svr_url = NULL;
char *svr_username = NULL;
char *svr_password = NULL;
char *svr_query = NULL;
char *svr_table = NULL;
char *svr_jarfile = NULL;
int svr_querytimeout = 0;
int svr_maxheapsize = 0;
/* Fetch options */
jdbcGetOptions(
RelationGetRelid(node->ss.ss_currentRelation),
&svr_drivername,
&svr_url,
&svr_querytimeout,
&svr_jarfile,
&svr_maxheapsize,
&svr_username,
&svr_password,
&svr_query,
&svr_table
);
SIGINTInterruptCheckProcess((jdbcFdwExecutionState **)&(node->fdw_state));
}
/*
* jdbcBeginForeignScan
* Initiate access to the database
*/
static void
jdbcBeginForeignScan(ForeignScanState *node, int eflags)
{
char *svr_drivername = NULL;
char *svr_url = NULL;
char *svr_username = NULL;
char *svr_password = NULL;
char *svr_query = NULL;
char *svr_table = NULL;
char *svr_jarfile = NULL;
int svr_querytimeout = 0;
int svr_maxheapsize = 0;
jdbcFdwExecutionState *festate;
char *query;
jobject java_call = NULL;
jclass JDBCUtilsClass;
jclass JavaString;
jstring StringArray[7];
jstring initialize_result = NULL;
jmethodID id_initialize;
jobjectArray arg_array;
int counter = 0;
int referencedeletecounter = 0;
jfieldID id_numberofcolumns;
char *querytimeoutstr = NULL;
char *jar_classpath;
char strpkglibdir[] = STR_PKGLIBDIR;
char *initialize_result_cstring = NULL;
SIGINTInterruptCheckProcess(NULL);
/* Fetch options */
jdbcGetOptions(
RelationGetRelid(node->ss.ss_currentRelation),
&svr_drivername,
&svr_url,
&svr_querytimeout,
&svr_jarfile,
&svr_maxheapsize,
&svr_username,
&svr_password,
&svr_query,
&svr_table
);
/* Build the query */
if (svr_query != NULL)
{
query = svr_query;
}
else
{
size_t len = strlen(svr_table) + 15;
query = (char *)palloc(len);
snprintf(query, len, "SELECT * FROM %s", svr_table);
}
/* Stash away the state info we have already */
festate = (jdbcFdwExecutionState *) palloc(sizeof(jdbcFdwExecutionState));
festate->query = query;
festate->NumberOfColumns = 0;
festate->NumberOfRows = 0;
/* Connect to the server and execute the query */
JDBCUtilsClass = (*env)->FindClass(env, "JDBCUtils");
if (JDBCUtilsClass == NULL)
{
elog(ERROR, "JDBCUtilsClass is NULL");
}
id_initialize = (*env)->GetMethodID(env, JDBCUtilsClass, "Initialize", "([Ljava/lang/String;)Ljava/lang/String;");
if (id_initialize == NULL)
{
elog(ERROR, "id_initialize is NULL");
}
id_numberofcolumns = (*env)->GetFieldID(env, JDBCUtilsClass, "NumberOfColumns" , "I");
if (id_numberofcolumns == NULL)
{
elog(ERROR, "id_numberofcolumns is NULL");
}
querytimeoutstr = (char*)palloc(sizeof(int));
jar_classpath = (char*)palloc(strlen(strpkglibdir) + strlen(svr_jarfile) + 2);
snprintf(querytimeoutstr, sizeof(int), "%d", svr_querytimeout);
snprintf(jar_classpath, (strlen(svr_jarfile) + 1), "%s", svr_jarfile);
if (svr_username == NULL)
{
svr_username = "";
}
if (svr_password == NULL)
{
svr_password = "";
}
StringArray[0] = (*env)->NewStringUTF(env, (festate->query));
StringArray[1] = (*env)->NewStringUTF(env, svr_drivername);
StringArray[2] = (*env)->NewStringUTF(env, svr_url);
StringArray[3] = (*env)->NewStringUTF(env, svr_username);
StringArray[4] = (*env)->NewStringUTF(env, svr_password);
StringArray[5] = (*env)->NewStringUTF(env, querytimeoutstr);
StringArray[6] = (*env)->NewStringUTF(env, jar_classpath);
JavaString = (*env)->FindClass(env, "java/lang/String");
arg_array = (*env)->NewObjectArray(env, 7, JavaString, StringArray[0]);
if (arg_array == NULL)
{
elog(ERROR, "arg_array is NULL");
}
for (counter = 1; counter < 7; counter++)
{
(*env)->SetObjectArrayElement(env, arg_array, counter, StringArray[counter]);
}
java_call = (*env)->AllocObject(env, JDBCUtilsClass);
if (java_call == NULL)
{
elog(ERROR, "java_call is NULL");
}
java_call = (*env)->NewGlobalRef(env, java_call);
if (java_call == NULL)
{
elog(ERROR, "global reference to java_call is NULL");
}
festate->java_call = java_call;
initialize_result = (*env)->CallObjectMethod(env, java_call, id_initialize, arg_array);
if (initialize_result != NULL)
{
initialize_result_cstring = ConvertStringToCString((jobject)initialize_result);
elog(ERROR, "%s", initialize_result_cstring);
}
node->fdw_state = (void *) festate;
festate->NumberOfColumns = (*env)->GetIntField(env, java_call, id_numberofcolumns);
for (referencedeletecounter = 0; referencedeletecounter < 7; referencedeletecounter++)
{
(*env)->DeleteLocalRef(env, StringArray[referencedeletecounter]);
}
(*env)->DeleteLocalRef(env, arg_array);
(*env)->ReleaseStringUTFChars(env, initialize_result, initialize_result_cstring);
(*env)->DeleteLocalRef(env, initialize_result);
}
/*
* jdbcIterateForeignScan
* Read next record from the data file and store it into the
* ScanTupleSlot as a virtual tuple
*/
static TupleTableSlot*
jdbcIterateForeignScan(ForeignScanState *node)
{
char **values;
HeapTuple tuple;
jmethodID id_returnresultseterrormessage;
jmethodID id_returnresultset;
jclass JDBCUtilsClass;
jobjectArray java_rowarray;
jstring error_message = NULL;
char *error_message_cstring = NULL;
int i = 0;
int j = 0;
jstring tempString;
jdbcFdwExecutionState *festate = (jdbcFdwExecutionState *) node->fdw_state;
TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
jobject java_call = festate->java_call;
/* Cleanup */
ExecClearTuple(slot);
SIGINTInterruptCheckProcess((jdbcFdwExecutionState **)&(node->fdw_state));
if ((*env)->PushLocalFrame(env, (festate->NumberOfColumns + 10)) < 0)
{
/* frame not pushed, no PopLocalFrame needed */
elog(ERROR, "Error");
}
JDBCUtilsClass = (*env)->FindClass(env, "JDBCUtils");
if (JDBCUtilsClass == NULL)
{
elog(ERROR, "JDBCUtilsClass is NULL");
}