forked from pgspider/jdbc_fdw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjq.c
1904 lines (1670 loc) · 53.4 KB
/
jq.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
/*
* --------------------------------------------- jq.c Implementation of Low
* level JDBC based functions replacing the libpq-fe functions
*
* Heimir Sverrisson, 2015-04-13
*
* Portions Copyright (c) 2021, TOSHIBA CORPORATION
*
* ---------------------------------------------
*/
#include "postgres.h"
#include "jdbc_fdw.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 "storage/ipc.h"
#include "utils/builtins.h"
#include "utils/datetime.h"
#include "utils/guc.h"
#include "utils/syscache.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "commands/defrem.h"
#include "libpq-fe.h"
#include "jni.h"
#define Str(arg) #arg
#define StrValue(arg) Str(arg)
#define STR_PKGLIBDIR StrValue(PKG_LIB_DIR)
/* Number of days from unix epoch time (1970-01-01) to postgres epoch time (2000-01-01) */
#define POSTGRES_TO_UNIX_EPOCH_DAYS (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE)
/* POSTGRES_TO_UNIX_EPOCH_DAYS to microseconds */
#define POSTGRES_TO_UNIX_EPOCH_USECS (POSTGRES_TO_UNIX_EPOCH_DAYS * USECS_PER_DAY)
#define JNI_VERSION JNI_VERSION_1_2
/*
* Local housekeeping functions and Java objects
*/
static __thread JNIEnv * Jenv = NULL;
static JavaVM * jvm;
jobject java_call;
static volatile 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 */
};
/*
* Structure holding options from the foreign server and user mapping
* definitions
*/
typedef struct JserverOptions
{
char *url;
char *drivername;
char *username;
char *password;
int querytimeout;
char *jarfile;
int maxheapsize;
} JserverOptions;
static JserverOptions opts;
/* Local function prototypes */
static int jdbc_connect_db_complete(Jconn * conn);
void jdbc_jvm_init(const ForeignServer * server, const UserMapping * user);
static void jdbc_get_server_options(JserverOptions * opts, const ForeignServer * f_server, const UserMapping * f_mapping);
static Jconn * jdbc_create_JDBC_connection(const ForeignServer * server, const UserMapping * user);
/*
* Uses a String object's content to create an instance of C String
*/
static char *jdbc_convert_string_to_cstring(jobject);
/*
* Convert byte array to Datum
*/
static Datum jdbc_convert_byte_array_to_datum(jbyteArray);
/*
* Common function to convert Object value to datum
*/
static Datum jdbc_convert_object_to_datum(Oid, int32, jobject);
/*
* JVM destroy function
*/
static void jdbc_destroy_jvm();
/*
* JVM attach function
*/
static void jdbc_attach_jvm();
/*
* JVM detach function
*/
static void jdbc_detach_jvm();
/*
* Get JNIEnv from JavaVM
*/
static void jdbc_get_jni_env(void);
/*
* Add classpath to system class loader using reflection
*/
static void jdbc_add_classpath_to_system_class_loader(char *classpath);
/*
* Get the maximum heap size for JVM by calling Runtime.getRuntime().maxMemory()
*/
static long jdbc_get_max_heap_size();
/*
* SIGINT interrupt check and process function
*/
static void jdbc_sig_int_interrupt_check_process();
/*
* clears any exception that is currently being thrown
*/
void jq_exception_clear(void);
/*
* check for pending exceptions
*/
void jq_get_exception(void);
/*
* get table infomations for importForeignSchema
*/
static List * jq_get_column_infos(Jconn * conn, char *tablename);
static List * jq_get_table_names(Jconn * conn);
static void jq_get_JDBCUtils(Jconn *conn, jclass *JDBCUtilsClass, jobject *JDBCUtilsObject);
/*
* jdbc_sig_int_interrupt_check_process Checks and processes if SIGINT
* interrupt occurs
*/
static void
jdbc_sig_int_interrupt_check_process()
{
if (InterruptFlag == true)
{
jclass JDBCUtilsClass;
jmethodID id_cancel;
JDBCUtilsClass = (*Jenv)->FindClass(Jenv, "JDBCUtils");
if (JDBCUtilsClass == NULL)
{
elog(ERROR, "JDBCUtilsClass is NULL");
}
id_cancel = (*Jenv)->GetMethodID(Jenv, JDBCUtilsClass, "cancel",
"()V");
if (id_cancel == NULL)
{
elog(ERROR, "id_cancel is NULL");
}
jq_exception_clear();
(*Jenv)->CallObjectMethod(Jenv, java_call, id_cancel);
jq_get_exception();
InterruptFlag = false;
elog(ERROR, "Query has been cancelled");
}
}
/*
* jdbc_convert_string_to_cstring Uses a String object passed as a jobject to
* the function to create an instance of C String.
*/
static char *
jdbc_convert_string_to_cstring(jobject java_cstring)
{
jclass JavaString;
char *StringPointer;
char *cString = NULL;
jdbc_sig_int_interrupt_check_process();
JavaString = (*Jenv)->FindClass(Jenv, "java/lang/String");
if (!((*Jenv)->IsInstanceOf(Jenv, java_cstring, JavaString)))
{
elog(ERROR, "Object not an instance of String class");
}
if (java_cstring != NULL)
{
StringPointer = (char *) (*Jenv)->GetStringUTFChars(Jenv,
(jstring) java_cstring, 0);
cString = pstrdup(StringPointer);
(*Jenv)->ReleaseStringUTFChars(Jenv, (jstring) java_cstring, StringPointer);
(*Jenv)->DeleteLocalRef(Jenv, java_cstring);
}
else
{
StringPointer = NULL;
}
return (cString);
}
/*
* jdbc_convert_byte_array_to_datum Uses a byte array object passed as a jbyteArray to
* the function to convert into Datum.
*/
static Datum
jdbc_convert_byte_array_to_datum(jbyteArray byteVal)
{
Datum valueDatum;
jbyte *buf = (*Jenv)->GetByteArrayElements(Jenv, byteVal, NULL);
jsize size = (*Jenv)->GetArrayLength(Jenv, byteVal);
jdbc_sig_int_interrupt_check_process();
if (buf == NULL)
return 0;
valueDatum = (Datum) palloc0(size + VARHDRSZ);
memcpy(VARDATA(valueDatum), buf, size);
SET_VARSIZE(valueDatum, size + VARHDRSZ);
return valueDatum;
}
/*
* jdbc_convert_object_to_datum Convert jobject to Datum value
*/
static Datum
jdbc_convert_object_to_datum(Oid pgtype, int32 pgtypmod, jobject obj)
{
switch (pgtype)
{
case BYTEAOID:
return jdbc_convert_byte_array_to_datum(obj);
default:
{
/*
* By default, data is retrieved as string and then
* convert to compatible data types
*/
char *value = jdbc_convert_string_to_cstring(obj);
if (value != NULL)
return jdbc_convert_to_pg(pgtype, pgtypmod, value);
else
/* Return 0 if value is NULL */
return 0;
}
}
}
/*
* jdbc_destroy_jvm Shuts down the JVM.
*/
static void
jdbc_destroy_jvm()
{
ereport(DEBUG3, (errmsg("In jdbc_destroy_jvm")));
(*jvm)->DestroyJavaVM(jvm);
}
/*
* jdbc_attach_jvm Attach the JVM.
*/
static void
jdbc_attach_jvm()
{
ereport(DEBUG3, (errmsg("In jdbc_attach_jvm")));
(*jvm)->AttachCurrentThread(jvm, (void **) &Jenv, NULL);
}
/*
* jdbc_detach_jvm Detach the JVM.
*/
static void
jdbc_detach_jvm()
{
ereport(DEBUG3, (errmsg("In jdbc_detach_jvm")));
(*jvm)->DetachCurrentThread(jvm);
}
static void jdbc_get_jni_env(void)
{
int JVMEnvStat;
ereport(DEBUG3, (errmsg("In jdbc_get_jni_env")));
JVMEnvStat = (*jvm)->GetEnv(jvm, (void **) &Jenv, JNI_VERSION);
if (JVMEnvStat == JNI_EDETACHED)
{
ereport(DEBUG3, (errmsg("JVMEnvStat: JNI_EDETACHED; the current thread is not attached to the VM")));
jdbc_attach_jvm();
}
else if (JVMEnvStat == JNI_OK)
{
ereport(DEBUG3, (errmsg("JVMEnvStat: JNI_OK")));
}
else if (JVMEnvStat == JNI_EVERSION)
{
ereport(ERROR, (errmsg("JVMEnvStat: JNI_EVERSION; the specified version is not supported")));
}
}
static void jdbc_add_classpath_to_system_class_loader(char *classpath)
{
int url_classpath_len;
char *url_classpath;
jclass ClassLoader_class;
jmethodID ClassLoader_getSystemClassLoader;
jobject system_class_loader;
jclass URLClassLoader_class;
jmethodID URLClassLoader_addURL;
jclass URL_class;
jmethodID URL_constructor;
jobject url;
ereport(DEBUG3, errmsg("In jdbc_add_classpath_to_system_class_loader"));
url_classpath_len = 5 + strlen(classpath) + 2; /* "file:" + classpath + '/\0' */
url_classpath = (char *)palloc0(url_classpath_len);
snprintf(url_classpath, url_classpath_len, "file:%s/", classpath);
ClassLoader_class = (*Jenv)->FindClass(Jenv, "java/lang/ClassLoader");
if (ClassLoader_class == NULL) {
ereport(ERROR, errmsg("java/lang/ClassLoader is not found"));
}
ClassLoader_getSystemClassLoader = (*Jenv)->GetStaticMethodID(Jenv, ClassLoader_class,
"getSystemClassLoader", "()Ljava/lang/ClassLoader;");
if (ClassLoader_getSystemClassLoader == NULL) {
ereport(ERROR, errmsg("ClassLoader.getSystemClassLoader is not found"));
}
URLClassLoader_class = (*Jenv)->FindClass(Jenv, "java/net/URLClassLoader");
if (URLClassLoader_class == NULL) {
ereport(ERROR, errmsg("java/net/URLClassLoader is not found"));
}
URLClassLoader_addURL = (*Jenv)->GetMethodID(Jenv, URLClassLoader_class,
"addURL", "(Ljava/net/URL;)V");
if (URLClassLoader_addURL == NULL) {
ereport(ERROR, errmsg("URLClassLoader.addURL is not found"));
}
URL_class = (*Jenv)->FindClass(Jenv, "java/net/URL");
if (URL_class == NULL) {
ereport(ERROR, errmsg("java/net/URL is not found"));
}
URL_constructor = (*Jenv)->GetMethodID(Jenv, URL_class,
"<init>", "(Ljava/lang/String;)V");
if (URL_constructor == NULL) {
ereport(ERROR, errmsg("URL.<init> is not found"));
}
jq_exception_clear();
system_class_loader = (*Jenv)->CallStaticObjectMethod(
Jenv, ClassLoader_class, ClassLoader_getSystemClassLoader);
jq_get_exception();
jq_exception_clear();
url = (*Jenv)->NewObject(Jenv, URL_class, URL_constructor, (*Jenv)->NewStringUTF(Jenv, url_classpath));
jq_get_exception();
jq_exception_clear();
(*Jenv)->CallVoidMethod(Jenv, system_class_loader, URLClassLoader_addURL, url);
jq_get_exception();
ereport(DEBUG3, errmsg("Add classpath to System Class Loader: %s", url_classpath));
}
static long jdbc_get_max_heap_size()
{
jclass Runtime_class;
jmethodID Runtime_getRuntime;
jobject runtime;
jmethodID Runtime_maxMemory;
jlong max_memory;
ereport(DEBUG3, errmsg("entering function %s", __func__));
Runtime_class = (*Jenv)->FindClass(Jenv, "java/lang/Runtime");
if (Runtime_class == NULL) {
ereport(ERROR, errmsg("java/lang/Runtime is not found"));
}
Runtime_getRuntime = (*Jenv)->GetStaticMethodID(Jenv, Runtime_class,
"getRuntime", "()Ljava/lang/Runtime;");
if (Runtime_getRuntime == NULL) {
ereport(ERROR, errmsg("Runtime.getRuntime is not found"));
}
Runtime_maxMemory = (*Jenv)->GetMethodID(Jenv, Runtime_class, "maxMemory", "()J");
if (Runtime_maxMemory == NULL) {
ereport(ERROR, errmsg("Runtime.maxMemory is not found"));
}
jq_exception_clear();
runtime = (*Jenv)->CallStaticObjectMethod(Jenv, Runtime_class,
Runtime_getRuntime);
jq_get_exception();
jq_exception_clear();
max_memory = (*Jenv)->CallLongMethod(Jenv, runtime, Runtime_maxMemory);
jq_get_exception();
return max_memory;
}
/*
* jdbc_jvm_init Create the JVM which will be used for calling the Java
* routines that use JDBC to connect and access the foreign database.
*
*/
void
jdbc_jvm_init(const ForeignServer * server, const UserMapping * user)
{
static bool FunctionCallCheck = false; /* This flag safeguards against
* multiple calls of
* jdbc_jvm_init() */
jint res = -5; /* Set to a negative value so we can see
* whether JVM has been correctly created or
* not */
JavaVMInitArgs vm_args;
JavaVMOption *options = NULL;
char strpkglibdir[] = STR_PKGLIBDIR;
char *maxheapsizeoption = NULL;
opts.maxheapsize = 0;
ereport(DEBUG3, (errmsg("In jdbc_jvm_init")));
jdbc_get_server_options(&opts, server, user); /* Get the maxheapsize
* value (if set) */
jdbc_sig_int_interrupt_check_process();
if (FunctionCallCheck == false)
{
if (opts.maxheapsize != 0)
{ /* If the user has given a value for setting
* the max heap size of the JVM */
options = (JavaVMOption *) palloc0(sizeof(JavaVMOption));
maxheapsizeoption = (char *) palloc0(sizeof(int) + 6);
snprintf(maxheapsizeoption, sizeof(int) + 6, "-Xmx%dm", opts.maxheapsize);
options[0].optionString = maxheapsizeoption;
vm_args.nOptions = 1;
}
else
{
vm_args.nOptions = 0;
}
vm_args.version = JNI_VERSION;
vm_args.options = options;
vm_args.ignoreUnrecognized = JNI_FALSE;
/* Create the Java VM */
res = JNI_CreateJavaVM(&jvm, (void **) &Jenv, &vm_args);
if (res == JNI_EEXIST) {
res = JNI_GetCreatedJavaVMs(&jvm, 1, NULL);
if (res < 0) {
ereport(ERROR, errmsg("Failed to get created Java VM"));
}
jdbc_get_jni_env();
jdbc_add_classpath_to_system_class_loader(strpkglibdir);
ereport(INFO, errmsg("Java VM has already been created by another extension. "
"The existing Java VM will be re-used. "
"The max heapsize may be different from the setting value. "
"The current max heapsize is %ld bytes", jdbc_get_max_heap_size()));
}
else if (res < 0)
{
ereport(ERROR, (errmsg("Failed to create Java VM")));
} else {
ereport(DEBUG3, (errmsg("Successfully created a JVM with %d MB heapsize", opts.maxheapsize)));
jdbc_add_classpath_to_system_class_loader(strpkglibdir);
}
InterruptFlag = false;
/* Register an on_proc_exit handler that shuts down the JVM. */
on_proc_exit(jdbc_destroy_jvm, 0);
FunctionCallCheck = true;
}
else
{
jdbc_get_jni_env();
}
}
/*
* Create an actual JDBC connection to the foreign server. Precondition:
* jdbc_jvm_init() has been successfully called. Returns: Jconn.status =
* CONNECTION_OK and a valid reference to a JDBCUtils class Error return:
* Jconn.status = CONNECTION_BAD
*/
static Jconn *
jdbc_create_JDBC_connection(const ForeignServer * server, const UserMapping * user)
{
jmethodID idCreate;
jstring stringArray[6];
jclass javaString;
jobjectArray argArray;
jclass JDBCUtilsClass;
jmethodID idGetIdentifierQuoteString;
jstring identifierQuoteString;
char *quote_string;
char *querytimeout_string;
int i;
int numParams = sizeof(stringArray) / sizeof(jstring); /* Number of parameters
* to Java */
int intSize = 10; /* The string size to allocate for an integer
* value */
int keyid = server->serverid; /* key for the hashtable in java
* depends on serverid */
MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext); /* Switch the memory context to TopMemoryContext to avoid the
* case connection is released when execution state finished */
Jconn *conn = (Jconn *) palloc0(sizeof(Jconn));
ereport(DEBUG3, (errmsg("In jdbc_create_JDBC_connection")));
conn->status = CONNECTION_BAD;
conn->festate = (jdbcFdwExecutionState *) palloc0(sizeof(jdbcFdwExecutionState));
conn->festate->query = NULL;
JDBCUtilsClass = (*Jenv)->FindClass(Jenv, "JDBCUtils");
if (JDBCUtilsClass == NULL)
{
ereport(ERROR, (errmsg("Failed to find the JDBCUtils class!")));
}
idCreate = (*Jenv)->GetMethodID(Jenv, JDBCUtilsClass, "createConnection",
"(I[Ljava/lang/String;)V");
if (idCreate == NULL)
{
ereport(ERROR, (errmsg("Failed to find the JDBCUtils.createConnection method!")));
}
idGetIdentifierQuoteString = (*Jenv)->GetMethodID(Jenv, JDBCUtilsClass, "getIdentifierQuoteString", "()Ljava/lang/String;");
if (idGetIdentifierQuoteString == NULL)
{
ereport(ERROR, (errmsg("Failed to find the JDBCUtils.getIdentifierQuoteString method")));
}
/*
* Construct the array to pass our parameters Query timeout is an int, we
* need a string
*/
querytimeout_string = (char *) palloc0(intSize);
snprintf(querytimeout_string, intSize, "%d", opts.querytimeout);
stringArray[0] = (*Jenv)->NewStringUTF(Jenv, opts.drivername);
stringArray[1] = (*Jenv)->NewStringUTF(Jenv, opts.url);
stringArray[2] = (*Jenv)->NewStringUTF(Jenv, opts.username);
stringArray[3] = (*Jenv)->NewStringUTF(Jenv, opts.password);
stringArray[4] = (*Jenv)->NewStringUTF(Jenv, querytimeout_string);
stringArray[5] = (*Jenv)->NewStringUTF(Jenv, opts.jarfile);
/* Set up the return value */
javaString = (*Jenv)->FindClass(Jenv, "java/lang/String");
argArray = (*Jenv)->NewObjectArray(Jenv, numParams, javaString, stringArray[0]);
if (argArray == NULL)
{
/* Return Java memory */
for (i = 0; i < numParams; i++)
{
(*Jenv)->DeleteLocalRef(Jenv, stringArray[i]);
}
ereport(ERROR, (errmsg("Failed to create argument array")));
}
for (i = 1; i < numParams; i++)
{
(*Jenv)->SetObjectArrayElement(Jenv, argArray, i, stringArray[i]);
}
conn->JDBCUtilsObject = (*Jenv)->AllocObject(Jenv, JDBCUtilsClass);
if (conn->JDBCUtilsObject == NULL)
{
/* Return Java memory */
for (i = 0; i < numParams; i++)
{
(*Jenv)->DeleteLocalRef(Jenv, stringArray[i]);
}
(*Jenv)->DeleteLocalRef(Jenv, argArray);
ereport(ERROR, (errmsg("Failed to create java call")));
}
jq_exception_clear();
(*Jenv)->CallObjectMethod(Jenv, conn->JDBCUtilsObject, idCreate, keyid, argArray);
jq_get_exception();
/* Return Java memory */
for (i = 0; i < numParams; i++)
{
(*Jenv)->DeleteLocalRef(Jenv, stringArray[i]);
}
(*Jenv)->DeleteLocalRef(Jenv, argArray);
ereport(DEBUG3, (errmsg("Created a JDBC connection: %s", opts.url)));
/* get default identifier quote string */
jq_exception_clear();
identifierQuoteString = (jstring) (*Jenv)->CallObjectMethod(Jenv, conn->JDBCUtilsObject, idGetIdentifierQuoteString);
jq_get_exception();
quote_string = jdbc_convert_string_to_cstring((jobject) identifierQuoteString);
conn->q_char = pstrdup(quote_string);
conn->status = CONNECTION_OK;
pfree(querytimeout_string);
/* Switch back to old context */
MemoryContextSwitchTo(oldcontext);
return conn;
}
/*
* Fetch the options for a jdbc_fdw foreign server and user mapping.
*/
static void
jdbc_get_server_options(JserverOptions * opts, const ForeignServer * f_server, const UserMapping * f_mapping)
{
List *options;
ListCell *lc;
/* Collect options from server and user mapping */
options = NIL;
options = list_concat(options, f_server->options);
options = list_concat(options, f_mapping->options);
/* Loop through the options, and get the values */
foreach(lc, options)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, "drivername") == 0)
{
opts->drivername = defGetString(def);
}
if (strcmp(def->defname, "username") == 0)
{
opts->username = defGetString(def);
}
if (strcmp(def->defname, "querytimeout") == 0)
{
opts->querytimeout = atoi(defGetString(def));
}
if (strcmp(def->defname, "jarfile") == 0)
{
opts->jarfile = defGetString(def);
}
if (strcmp(def->defname, "maxheapsize") == 0)
{
opts->maxheapsize = atoi(defGetString(def));
}
if (strcmp(def->defname, "password") == 0)
{
opts->password = defGetString(def);
}
if (strcmp(def->defname, "url") == 0)
{
opts->url = defGetString(def);
}
}
}
Jresult *
jq_exec(Jconn * conn, const char *query)
{
jmethodID idCreateStatement;
jstring statement;
jclass JDBCUtilsClass;
jobject JDBCUtilsObject;
Jresult *res;
ereport(DEBUG3, (errmsg("In jq_exec(%p): %s", conn, query)));
jq_get_JDBCUtils(conn, &JDBCUtilsClass, &JDBCUtilsObject);
res = (Jresult *) palloc0(sizeof(Jresult));
*res = PGRES_FATAL_ERROR;
idCreateStatement = (*Jenv)->GetMethodID(Jenv, JDBCUtilsClass, "createStatement",
"(Ljava/lang/String;)V");
if (idCreateStatement == NULL)
{
ereport(ERROR, (errmsg("Failed to find the JDBCUtils.createStatement method!")));
}
/* The query argument */
statement = (*Jenv)->NewStringUTF(Jenv, query);
if (statement == NULL)
{
ereport(ERROR, (errmsg("Failed to create query argument")));
}
jq_exception_clear();
(*Jenv)->CallObjectMethod(Jenv, conn->JDBCUtilsObject, idCreateStatement, statement);
jq_get_exception();
/* Return Java memory */
(*Jenv)->DeleteLocalRef(Jenv, statement);
*res = PGRES_COMMAND_OK;
return res;
}
Jresult *
jq_exec_id(Jconn * conn, const char *query, int *resultSetID)
{
jmethodID idCreateStatementID;
jstring statement;
jclass JDBCUtilsClass;
jobject JDBCUtilsObject;
Jresult *res;
ereport(DEBUG3, (errmsg("In jq_exec_id(%p): %s", conn, query)));
jq_get_JDBCUtils(conn, &JDBCUtilsClass, &JDBCUtilsObject);
res = (Jresult *) palloc0(sizeof(Jresult));
*res = PGRES_FATAL_ERROR;
idCreateStatementID = (*Jenv)->GetMethodID(Jenv, JDBCUtilsClass, "createStatementID",
"(Ljava/lang/String;)I");
if (idCreateStatementID == NULL)
{
ereport(ERROR, (errmsg("Failed to find the JDBCUtils.createStatementID method!")));
}
/* The query argument */
statement = (*Jenv)->NewStringUTF(Jenv, query);
if (statement == NULL)
{
ereport(ERROR, (errmsg("Failed to create query argument")));
}
jq_exception_clear();
*resultSetID = (int) (*Jenv)->CallIntMethod(Jenv, conn->JDBCUtilsObject, idCreateStatementID, statement);
jq_get_exception();
if (*resultSetID < 0)
{
/* Return Java memory */
(*Jenv)->DeleteLocalRef(Jenv, statement);
ereport(ERROR, (errmsg("Get resultSetID failed with code: %d", *resultSetID)));
}
ereport(DEBUG3, (errmsg("Get resultSetID successfully, ID: %d", *resultSetID)));
/* Return Java memory */
(*Jenv)->DeleteLocalRef(Jenv, statement);
*res = PGRES_COMMAND_OK;
return res;
}
void *
jq_release_resultset_id(Jconn * conn, int resultSetID)
{
jmethodID idClearResultSetID;
jclass JDBCUtilsClass;
jobject JDBCUtilsObject;
ereport(DEBUG3, (errmsg("In jq_release_resultset_id: %d", resultSetID)));
jq_get_JDBCUtils(conn, &JDBCUtilsClass, &JDBCUtilsObject);
idClearResultSetID = (*Jenv)->GetMethodID(Jenv, JDBCUtilsClass, "clearResultSetID",
"(I)V");
if (idClearResultSetID == NULL)
{
ereport(ERROR, (errmsg("Failed to find the JDBCUtils.clearResultSetID method!")));
}
jq_exception_clear();
(*Jenv)->CallObjectMethod(Jenv, conn->JDBCUtilsObject, idClearResultSetID, resultSetID);
jq_get_exception();
return NULL;
}
/*
* jq_iterate: Read the next row from the remote server
*/
TupleTableSlot *
jq_iterate(Jconn * conn, ForeignScanState * node, List * retrieved_attrs, int resultSetID)
{
jobject JDBCUtilsObject;
TupleTableSlot *tupleSlot = node->ss.ss_ScanTupleSlot;
TupleDesc tupleDescriptor = tupleSlot->tts_tupleDescriptor;
jclass JDBCUtilsClass;
jmethodID idResultSet;
jmethodID idNumberOfColumns;
jobjectArray rowArray;
char **values;
int numberOfColumns;
int i;
ereport(DEBUG3, (errmsg("In jq_iterate")));
memset(tupleSlot->tts_values, 0, sizeof(Datum) * tupleDescriptor->natts);
memset(tupleSlot->tts_isnull, true, sizeof(bool) * tupleDescriptor->natts);
jq_get_JDBCUtils(conn, &JDBCUtilsClass, &JDBCUtilsObject);
ExecClearTuple(tupleSlot);
jdbc_sig_int_interrupt_check_process();
idNumberOfColumns = (*Jenv)->GetMethodID(Jenv, JDBCUtilsClass, "getNumberOfColumns", "(I)I");
if (idNumberOfColumns == NULL)
{
ereport(ERROR, (errmsg("Failed to find the JDBCUtils.getNumberOfColumns method")));
}
jq_exception_clear();
numberOfColumns = (int) (*Jenv)->CallIntMethod(Jenv, conn->JDBCUtilsObject, idNumberOfColumns, resultSetID);
jq_get_exception();
if (numberOfColumns < 0)
{
ereport(ERROR, (errmsg("getNumberOfColumns got wrong value: %d", numberOfColumns)));
}
if ((*Jenv)->PushLocalFrame(Jenv, (numberOfColumns + 10)) < 0)
{
ereport(ERROR, (errmsg("Error pushing local java frame")));
}
idResultSet = (*Jenv)->GetMethodID(Jenv, JDBCUtilsClass, "getResultSet", "(I)[Ljava/lang/Object;");
if (idResultSet == NULL)
{
ereport(ERROR, (errmsg("Failed to find the JDBCUtils.getResultSet method!")));
}
/* Allocate pointers to the row data */
jq_exception_clear();
rowArray = (*Jenv)->CallObjectMethod(Jenv, JDBCUtilsObject, idResultSet, resultSetID);
jq_get_exception();
if (rowArray != NULL)
{
if(retrieved_attrs != NIL){
values = (char **) palloc0(tupleDescriptor->natts * sizeof(char *));
for (i = 0; i < retrieved_attrs->length; i++)
{
int column_index = retrieved_attrs->elements[i].int_value - 1;
Oid pgtype = TupleDescAttr(tupleDescriptor, column_index)->atttypid;
int32 pgtypmod = TupleDescAttr(tupleDescriptor, column_index)->atttypmod;
jobject obj = (jobject) (*Jenv)->GetObjectArrayElement(Jenv, rowArray, i);
if (obj != NULL)
{
tupleSlot->tts_isnull[column_index] = false;
tupleSlot->tts_values[column_index] = jdbc_convert_object_to_datum(pgtype, pgtypmod, obj);
}
}
}else{
jsize size = (*Jenv)->GetArrayLength(Jenv, rowArray);
memset(tupleSlot->tts_values, 0, sizeof(Datum) * (int)size);
memset(tupleSlot->tts_isnull, true, sizeof(bool) * (int)size);
ExecClearTuple(tupleSlot);
values = (char **) palloc0(size * sizeof(char *));
for (i = 0; i < size; i++)
{
values[i] = jdbc_convert_string_to_cstring((jobject) (*Jenv)->GetObjectArrayElement(Jenv, rowArray, i));
if (values[i] != NULL)
{
tupleSlot->tts_isnull[i] = false;
tupleSlot->tts_values[i] = *values[i];
}
}
}
ExecStoreVirtualTuple(tupleSlot);
(*Jenv)->DeleteLocalRef(Jenv, rowArray);
}
(*Jenv)->PopLocalFrame(Jenv, NULL);
return (tupleSlot);
}
/*
* jq_iterate_all_row: Read the all row from the remote server without an existing foreign table
*/
void
jq_iterate_all_row(FunctionCallInfo fcinfo, Jconn * conn, TupleDesc tupleDescriptor, int resultSetID)
{
ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
jobject JDBCUtilsObject;
jclass JDBCUtilsClass;
jmethodID idResultSet;
jmethodID idNumberOfColumns;
jobjectArray rowArray;
Tuplestorestate *tupstore;
HeapTuple tuple;
MemoryContext oldcontext;
Datum *values;
bool *nulls;
int numberOfColumns;
ereport(DEBUG3, (errmsg("In jq_iterate_all_row")));
oldcontext = MemoryContextSwitchTo(rsinfo->econtext->ecxt_per_query_memory);
tupstore = tuplestore_begin_heap(true, false, work_mem);
jq_get_JDBCUtils(conn, &JDBCUtilsClass, &JDBCUtilsObject);
jdbc_sig_int_interrupt_check_process();
idNumberOfColumns = (*Jenv)->GetMethodID(Jenv, JDBCUtilsClass, "getNumberOfColumns", "(I)I");
if (idNumberOfColumns == NULL)
{
ereport(ERROR, (errmsg("Failed to find the JDBCUtils.getNumberOfColumns method")));
}
jq_exception_clear();
numberOfColumns = (int) (*Jenv)->CallIntMethod(Jenv, conn->JDBCUtilsObject, idNumberOfColumns, resultSetID);
jq_get_exception();
if (numberOfColumns < 0)
{
ereport(ERROR, (errmsg("getNumberOfColumns got wrong value: %d", numberOfColumns)));
}
if ((*Jenv)->PushLocalFrame(Jenv, (numberOfColumns + 10)) < 0)
{
ereport(ERROR, (errmsg("Error pushing local java frame")));
}
idResultSet = (*Jenv)->GetMethodID(Jenv, JDBCUtilsClass, "getResultSet", "(I)[Ljava/lang/Object;");
if (idResultSet == NULL)
{
ereport(ERROR, (errmsg("Failed to find the JDBCUtils.getResultSet method!")));
}
do
{
/* Allocate pointers to the row data */
jq_exception_clear();
rowArray = (*Jenv)->CallObjectMethod(Jenv, JDBCUtilsObject, idResultSet, resultSetID);
jq_get_exception();
if (rowArray != NULL)
{
values = (Datum *) palloc0(tupleDescriptor->natts * sizeof(Datum));
nulls = (bool *) palloc(tupleDescriptor->natts * sizeof(bool));
/* Initialize to nulls for any columns not present in result */
memset(nulls, true, tupleDescriptor->natts * sizeof(bool));
for (int i = 0; i < numberOfColumns; i++)
{
int column_index = i;
Oid pgtype = TupleDescAttr(tupleDescriptor, column_index)->atttypid;
int32 pgtypmod = TupleDescAttr(tupleDescriptor, column_index)->atttypmod;
jobject obj = (jobject) (*Jenv)->GetObjectArrayElement(Jenv, rowArray, i);
if (obj != NULL)
{
values[column_index] = jdbc_convert_object_to_datum(pgtype, pgtypmod, obj);
nulls[column_index] = false;
}
}
tuple = heap_form_tuple(tupleDescriptor, values, nulls);
tuplestore_puttuple(tupstore, tuple);
(*Jenv)->DeleteLocalRef(Jenv, rowArray);
}
}
while (rowArray != NULL);
if (tuple != NULL)
{
rsinfo->setResult = tupstore;
rsinfo->setDesc = tupleDescriptor;
MemoryContextSwitchTo(oldcontext);
}
(*Jenv)->PopLocalFrame(Jenv, NULL);
}
Jresult *
jq_exec_prepared(Jconn * conn, const int *paramLengths,
const int *paramFormats, int resultFormat, int resultSetID)
{
jmethodID idExecPreparedStatement;
jclass JDBCUtilsClass;
jobject JDBCUtilsObject;
Jresult *res;
ereport(DEBUG3, (errmsg("In jq_exec_prepared")));
jq_get_JDBCUtils(conn, &JDBCUtilsClass, &JDBCUtilsObject);
res = (Jresult *) palloc0(sizeof(Jresult));
*res = PGRES_FATAL_ERROR;
idExecPreparedStatement = (*Jenv)->GetMethodID(Jenv, JDBCUtilsClass, "execPreparedStatement",
"(I)V");
if (idExecPreparedStatement == NULL)
{
ereport(ERROR, (errmsg("Failed to find the JDBCUtils.execPreparedStatement method!")));
}
jq_exception_clear();
(*Jenv)->CallObjectMethod(Jenv, conn->JDBCUtilsObject, idExecPreparedStatement, resultSetID);
jq_get_exception();
/* Return Java memory */
*res = PGRES_COMMAND_OK;