-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathFunction.c
More file actions
1420 lines (1257 loc) · 42.3 KB
/
Function.c
File metadata and controls
1420 lines (1257 loc) · 42.3 KB
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
/*
* Copyright (c) 2004-2023 Tada AB and other contributors, as listed below.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the The BSD 3-Clause License
* which accompanies this distribution, and is available at
* http://opensource.org/licenses/BSD-3-Clause
*
* Contributors:
* Thomas Hallgren
* Chapman Flack
*/
#include "org_postgresql_pljava_internal_Function.h"
#include "org_postgresql_pljava_internal_Function_EarlyNatives.h"
#include "pljava/PgObject_priv.h"
#include "pljava/Exception.h"
#include "pljava/InstallHelper.h"
#include "pljava/Invocation.h"
#include "pljava/Function.h"
#include "pljava/HashMap.h"
#include "pljava/Iterator.h"
#include "pljava/JNICalls.h"
#include "pljava/type/Composite.h"
#include "pljava/type/Oid.h"
#include "pljava/type/String.h"
#include "pljava/type/TriggerData.h"
#include "pljava/type/UDT.h"
#include <catalog/pg_proc.h>
#include <catalog/pg_language.h>
#include <catalog/pg_namespace.h>
#include <utils/builtins.h>
#include <ctype.h>
#include <funcapi.h>
#include <utils/typcache.h>
#if PG_VERSION_NUM >= 160000
#define PG_FUNCNAME_MACRO __func__
#endif
#ifdef _MSC_VER
# define strcasecmp _stricmp
# define strncasecmp _strnicmp
#endif
#define PARAM_OIDS(procStruct) (procStruct)->proargtypes.values
#define COUNTCHECK(refs, prims) ((jshort)(((refs) << 8) | ((prims) & 0xff)))
jobject pljava_Function_NO_LOADER;
static jclass s_Function_class;
static jclass s_ParameterFrame_class;
static jclass s_EntryPoints_class;
static jmethodID s_Function_create;
static jmethodID s_Function_getClassIfUDT;
static jmethodID s_Function_udtReadHandle;
static jmethodID s_Function_udtParseHandle;
static jmethodID s_Function_udtWriteHandle;
static jmethodID s_Function_udtToStringHandle;
static jmethodID s_ParameterFrame_push;
static jmethodID s_ParameterFrame_pop;
static jmethodID s_EntryPoints_invoke;
static jmethodID s_EntryPoints_udtWriteInvoke;
static jmethodID s_EntryPoints_udtToStringInvoke;
static jmethodID s_EntryPoints_udtReadInvoke;
static jmethodID s_EntryPoints_udtParseInvoke;
static PgObjectClass s_FunctionClass;
static Type s_pgproc_Type;
static inline Datum invokeTrigger(Function self, PG_FUNCTION_ARGS);
static jobjectArray s_referenceParameters;
static jvalue s_primitiveParameters [ 1 + 255 ];
static jshort * const s_countCheck =
(jshort *)(((char *)s_primitiveParameters) +
org_postgresql_pljava_internal_Function_s_offset_paramCounts);
struct Function_
{
struct PgObject_ PgObject_extension;
/**
* True if the function is not a volatile function (i.e. STABLE or
* IMMUTABLE). This means that the function is not allowed to have
* side effects.
*/
bool readOnly;
/**
* True if this is a UDT function (input/output/receive/send)
*/
bool isUDT;
/**
* Java class, i.e. the UDT class or the class where the static method
* is defined.
*/
jclass clazz;
/**
* Global reference to the class loader for the schema in which this
* function is declared.
*/
jobject schemaLoader;
union
{
struct
{
/*
* True if the function is a multi-call function and hence, will
* allocate a memory context of its own.
*/
bool isMultiCall;
/*
* The number of reference parameters
*/
uint16 numRefParams;
/*
* The number of primitive parameters
*/
uint16 numPrimParams;
/*
* Array containing one type for eeach parameter.
*/
Type* paramTypes;
/*
* The return type.
*/
Type returnType;
/*
* The type map used when mapping parameter and return types. We
* need to store it here in order to cope with dynamic types (any
* and anyarray). This is now slightly redundant, as it could be got
* from schemaLoader at the cost of a couple JNI calls, but this was
* here first.
*/
jobject typeMap;
/**
* EntryPoints.Invocable to the resolved Java method implementing
* the function.
*/
jobject invocable;
} nonudt;
struct
{
/**
* The UDT that this function is associated with
*/
UDT udt;
/**
* The UDT function to call
*/
UDTFunction udtFunction;
} udt;
} func;
};
/*
* Not fussing with initializer, relying on readOnly being false by C static
* initial default.
*/
static struct Function_ s_initWriter;
Function Function_INIT_WRITER = &s_initWriter;
static HashMap s_funcMap = 0;
static void _Function_finalize(PgObject func)
{
Function self = (Function)func;
JNI_deleteGlobalRef(self->clazz);
JNI_deleteGlobalRef(self->schemaLoader);
if(!self->isUDT)
{
JNI_deleteGlobalRef(self->func.nonudt.invocable);
if(self->func.nonudt.typeMap != 0)
JNI_deleteGlobalRef(self->func.nonudt.typeMap);
if(self->func.nonudt.paramTypes != 0)
pfree(self->func.nonudt.paramTypes);
}
}
extern void Function_initialize(void);
void Function_initialize(void)
{
JNINativeMethod earlyMethods[] =
{
{
"_parameterArea",
"([Ljava/lang/Object;)Ljava/nio/ByteBuffer;",
Java_org_postgresql_pljava_internal_Function_00024EarlyNatives__1parameterArea
},
{ 0, 0, 0 }
};
JNINativeMethod functionMethods[] =
{
{
"_storeToNonUDT",
"(JLjava/lang/ClassLoader;Ljava/lang/Class;ZZLjava/util/Map;IILjava/lang/String;[I[Ljava/lang/String;[Ljava/lang/String;)Z",
Java_org_postgresql_pljava_internal_Function__1storeToNonUDT
},
{
"_storeToUDT",
"(JLjava/lang/ClassLoader;Ljava/lang/Class;ZII"
")V",
Java_org_postgresql_pljava_internal_Function__1storeToUDT
},
{
"_reconcileTypes",
"(J[Ljava/lang/String;[Ljava/lang/String;I)V",
Java_org_postgresql_pljava_internal_Function__1reconcileTypes
},
{ 0, 0, 0 }
};
jclass cls;
jfieldID fld;
StaticAssertStmt(org_postgresql_pljava_internal_Function_s_sizeof_jvalue
== sizeof (jvalue), "Function.java has wrong size for Java JNI jvalue");
s_funcMap = HashMap_create(59, TopMemoryContext);
cls = PgObject_getJavaClass(
"org/postgresql/pljava/internal/Function$EarlyNatives");
PgObject_registerNatives2(cls, earlyMethods);
JNI_deleteLocalRef(cls);
s_ParameterFrame_class = JNI_newGlobalRef(PgObject_getJavaClass(
"org/postgresql/pljava/internal/Function$ParameterFrame"));
s_ParameterFrame_push = PgObject_getStaticJavaMethod(s_ParameterFrame_class,
"push", "()V");
s_ParameterFrame_pop = PgObject_getStaticJavaMethod(s_ParameterFrame_class,
"pop", "()V");
s_Function_class = JNI_newGlobalRef(PgObject_getJavaClass(
"org/postgresql/pljava/internal/Function"));
s_Function_create = PgObject_getStaticJavaMethod(s_Function_class, "create",
"(JLjava/sql/ResultSet;Ljava/lang/String;Ljava/lang/String;ZZZZ)"
"Lorg/postgresql/pljava/internal/EntryPoints$Invocable;");
s_Function_getClassIfUDT = PgObject_getStaticJavaMethod(s_Function_class,
"getClassIfUDT",
"(Ljava/sql/ResultSet;Ljava/lang/String;)"
"Ljava/lang/Class;");
s_EntryPoints_class = JNI_newGlobalRef(PgObject_getJavaClass(
"org/postgresql/pljava/internal/EntryPoints"));
s_EntryPoints_invoke = PgObject_getStaticJavaMethod(
s_EntryPoints_class,
"invoke",
"(Lorg/postgresql/pljava/internal/EntryPoints$Invocable;)"
"Ljava/lang/Object;");
s_EntryPoints_udtWriteInvoke = PgObject_getStaticJavaMethod(
s_EntryPoints_class,
"udtWriteInvoke",
"(Lorg/postgresql/pljava/internal/EntryPoints$Invocable;"
"Ljava/sql/SQLData;Ljava/sql/SQLOutput;"
")V");
s_EntryPoints_udtToStringInvoke = PgObject_getStaticJavaMethod(
s_EntryPoints_class,
"udtToStringInvoke",
"(Lorg/postgresql/pljava/internal/EntryPoints$Invocable;"
"Ljava/sql/SQLData;)Ljava/lang/String;");
s_EntryPoints_udtReadInvoke = PgObject_getStaticJavaMethod(
s_EntryPoints_class,
"udtReadInvoke",
"(Lorg/postgresql/pljava/internal/EntryPoints$Invocable;"
"Ljava/sql/SQLInput;"
"Ljava/lang/String;)Ljava/sql/SQLData;");
s_EntryPoints_udtParseInvoke = PgObject_getStaticJavaMethod(
s_EntryPoints_class,
"udtParseInvoke",
"(Lorg/postgresql/pljava/internal/EntryPoints$Invocable;"
"Ljava/lang/String;"
"Ljava/lang/String;)Ljava/sql/SQLData;");
s_Function_udtReadHandle = PgObject_getStaticJavaMethod(s_Function_class,
"udtReadHandle", "(Ljava/lang/Class;Ljava/lang/String;Z)"
"Lorg/postgresql/pljava/internal/EntryPoints$Invocable;");
s_Function_udtParseHandle = PgObject_getStaticJavaMethod(s_Function_class,
"udtParseHandle", "(Ljava/lang/Class;Ljava/lang/String;Z)"
"Lorg/postgresql/pljava/internal/EntryPoints$Invocable;");
s_Function_udtWriteHandle = PgObject_getStaticJavaMethod(s_Function_class,
"udtWriteHandle", "(Ljava/lang/Class;Ljava/lang/String;Z)"
"Lorg/postgresql/pljava/internal/EntryPoints$Invocable;");
s_Function_udtToStringHandle =
PgObject_getStaticJavaMethod(s_Function_class,
"udtToStringHandle", "(Ljava/lang/Class;Ljava/lang/String;Z)"
"Lorg/postgresql/pljava/internal/EntryPoints$Invocable;");
PgObject_registerNatives2(s_Function_class, functionMethods);
cls = PgObject_getJavaClass("org/postgresql/pljava/sqlj/Loader");
fld = PgObject_getStaticJavaField(cls,
"SENTINEL", "Ljava/lang/ClassLoader;");
pljava_Function_NO_LOADER =
JNI_newGlobalRef(JNI_getStaticObjectField(cls, fld));
JNI_deleteLocalRef(cls);
s_FunctionClass = PgObjectClass_create("Function", sizeof(struct Function_), _Function_finalize);
s_pgproc_Type = Composite_obtain(ProcedureRelation_Rowtype_Id);
}
jobject pljava_Function_refInvoke(Function self)
{
return JNI_callStaticObjectMethod(s_EntryPoints_class,
s_EntryPoints_invoke, self->func.nonudt.invocable);
}
void pljava_Function_voidInvoke(Function self)
{
JNI_callStaticObjectMethod(s_EntryPoints_class,
s_EntryPoints_invoke, self->func.nonudt.invocable);
}
jboolean pljava_Function_booleanInvoke(Function self)
{
JNI_callStaticObjectMethod(s_EntryPoints_class,
s_EntryPoints_invoke, self->func.nonudt.invocable);
return s_primitiveParameters[0].z;
}
jbyte pljava_Function_byteInvoke(Function self)
{
JNI_callStaticObjectMethod(s_EntryPoints_class,
s_EntryPoints_invoke, self->func.nonudt.invocable);
return s_primitiveParameters[0].b;
}
jshort pljava_Function_shortInvoke(Function self)
{
JNI_callStaticObjectMethod(s_EntryPoints_class,
s_EntryPoints_invoke, self->func.nonudt.invocable);
return s_primitiveParameters[0].s;
}
jchar pljava_Function_charInvoke(Function self)
{
JNI_callStaticObjectMethod(s_EntryPoints_class,
s_EntryPoints_invoke, self->func.nonudt.invocable);
return s_primitiveParameters[0].c;
}
jint pljava_Function_intInvoke(Function self)
{
JNI_callStaticObjectMethod(s_EntryPoints_class,
s_EntryPoints_invoke, self->func.nonudt.invocable);
return s_primitiveParameters[0].i;
}
jfloat pljava_Function_floatInvoke(Function self)
{
JNI_callStaticObjectMethod(s_EntryPoints_class,
s_EntryPoints_invoke, self->func.nonudt.invocable);
return s_primitiveParameters[0].f;
}
jlong pljava_Function_longInvoke(Function self)
{
JNI_callStaticObjectMethod(s_EntryPoints_class,
s_EntryPoints_invoke, self->func.nonudt.invocable);
return s_primitiveParameters[0].j;
}
jdouble pljava_Function_doubleInvoke(Function self)
{
JNI_callStaticObjectMethod(s_EntryPoints_class,
s_EntryPoints_invoke, self->func.nonudt.invocable);
return s_primitiveParameters[0].d;
}
/*
* 'Reserve' the static parameter frame for (refArgCount,primArgCount) reference
* and primitive parameters, respectively, pushing temporarily out of the way
* any current contents, detected by a non-(0,0) existing reservation. Returns
* the sum of its two arguments.
*
* The corresponding pop of the earlier contents will happen at
* Invocation_popInvocation time, so this scheme is only appropriately used for
* calls that happen within the scope of an Invocation, as conventional PL/Java
* function calls do.
*
* It is possible to reserve (0,0) space, though no existing frame will be
* saved/restored in that case. Caution: the two count arguments here count only
* parameters, not the possibility that a primitive-returning function uses a
* slot in the frame for its return. The primitive call wrappers must make their
* own arrangements to save the typically-only-one-jvalue affected by that use
* and restore it on both normal and exceptional return paths. To streamline the
* most common case, Invocation_{push,pop}Invocation will unconditionally save
* the first jvalue slot, and restore it if the more heavyweight frame-pushing
* has not been used. That spares a primitive call wrapper the cycles of
* managing another PG_TRY block. Any wrapper that will use more than the first
* jvalue slot for returns, though, must handle its own normal and exceptional
* cleanup.
*/
static inline jsize
reserveParameterFrame(jsize refArgCount, jsize primArgCount)
{
jshort newCounts = COUNTCHECK(refArgCount, primArgCount);
/* The *s_countCheck field in the parameter area will be zero unless
* this is a recursive invocation (believed only possible via a UDT
* function called while converting the parameters for some outer
* invocation). It could also be zero if this is a recursive invocation
* but the outer one involves no parameters, which won't happen if UDT
* conversion for a parameter is the only way to get here, and even if
* it happens, we still don't need to save its frame because there is
* nothing there that we'll clobber.
*/
if ( 0 != newCounts && 0 != *s_countCheck )
{
JNI_callStaticVoidMethodLocked(
s_ParameterFrame_class, s_ParameterFrame_push);
/* Record, in currentInvocation, that a frame was pushed; the pop
* will happen in Invocation_popInvocation, which our caller
* arranges for both normal return and PG_CATCH cases.
*/
currentInvocation->frameLimits = FRAME_LIMITS_PUSHED;
}
*s_countCheck = newCounts;
return refArgCount + primArgCount;
}
/*
* This should happen everywhere reserveParameterFrame happens, but is factored
* out to allow a couple of call sites to optimize out one or the other. As with
* reserveParameterFrame, the undoing of this happens in popFrame below.
*
* currentInvocation->savedLoader can have a "not known" value (which has to be
* distinct from null, because null is a perfectly cromulent context classloader
* as far as Java is concerned). Leaving it that way will mean no restoration at
* popInvocation time. The loaderUpdater may leave it that way in some cases,
* in a bid to reduce overhead if the same loader's wanted again.
*/
static inline void
installContextLoader(Function self)
{
(*JNI_loaderUpdater)(self->schemaLoader);
}
/*
* Not intended for any caller but Invocation_popInvocation.
*/
void pljava_Function_popFrame(bool heavy)
{
if ( heavy )
JNI_callStaticVoidMethod(s_ParameterFrame_class, s_ParameterFrame_pop);
if ( pljava_Function_NO_LOADER == currentInvocation->savedLoader )
return;
(*JNI_loaderRestorer)();
}
/*
* Invoke an Invocable that was obtained by invoking an Invocable for a
* set-returning-function that returns results in value-per-call style.
* Pass true for 'close' when no more results are wanted. Will always overwrite
* *result; check the boolean return value to determine whether that is a real
* result (true) or the end of results was reached (false).
*/
jboolean pljava_Function_vpcInvoke(
Function self, jobject invocable, jobject rowcollect, jlong call_cntr,
jboolean close, jobject *result)
{
/*
* When retrieving the very first row, this call happens under the same
* Invocation as the call to the user function itself that returned this
* invocable (and may, rarely, have pushed a ParameterFrame). What does
* the reservation below imply for ParameterFrame management?
*
* It's ok, because the user function's invocation will have cleared the
* static area parameter counts; this reservation will therefore not see a
* need to push a frame. If one was pushed for the user function itself, it
* remains on top, to be popped when the Invocation is.
*/
reserveParameterFrame(1, 2);
JNI_setObjectArrayElement(s_referenceParameters, 0, rowcollect);
s_primitiveParameters[0].j = call_cntr;
s_primitiveParameters[1].z = close;
*result = JNI_callStaticObjectMethod(s_EntryPoints_class,
s_EntryPoints_invoke, invocable);
return s_primitiveParameters[0].z;
}
void pljava_Function_udtWriteInvoke(
jobject invocable, jobject value, jobject stream)
{
JNI_callStaticVoidMethod(s_EntryPoints_class,
s_EntryPoints_udtWriteInvoke, invocable, value, stream);
}
jstring pljava_Function_udtToStringInvoke(jobject invocable, jobject value)
{
return JNI_callStaticObjectMethod(s_EntryPoints_class,
s_EntryPoints_udtToStringInvoke, invocable, value);
}
jobject pljava_Function_udtReadInvoke(
jobject invocable, jobject stream, jstring typeName)
{
return JNI_callStaticObjectMethod(s_EntryPoints_class,
s_EntryPoints_udtReadInvoke, invocable, stream, typeName);
}
jobject pljava_Function_udtParseInvoke(
jobject parseInvocable, jstring stringRep, jstring typeName)
{
return JNI_callStaticObjectMethod(s_EntryPoints_class,
s_EntryPoints_udtParseInvoke, parseInvocable, stringRep, typeName);
}
static jobject obtainUDTHandle(
jmethodID which, jclass clazz, char *langName, bool trusted);
jobject pljava_Function_udtReadHandle(
jclass clazz, char *langName, bool trusted)
{
return obtainUDTHandle(
s_Function_udtReadHandle, clazz, langName, trusted);
}
jobject pljava_Function_udtWriteHandle(
jclass clazz, char *langName, bool trusted)
{
return obtainUDTHandle(
s_Function_udtWriteHandle, clazz, langName, trusted);
}
static inline jobject
obtainUDTHandle(
jmethodID which, jclass clazz, char *langName, bool trusted)
{
jstring jname = String_createJavaStringFromNTS(langName);
jobject result = JNI_callStaticObjectMethod(s_Function_class,
which, clazz, jname, trusted ? JNI_TRUE : JNI_FALSE);
JNI_deleteLocalRef(jname);
return result;
}
static inline jstring
getSchemaName(int namespaceOid)
{
HeapTuple nspTup = PgObject_getValidTuple(NAMESPACEOID, namespaceOid, "namespace");
Form_pg_namespace nspStruct = (Form_pg_namespace)GETSTRUCT(nspTup);
jstring schemaName = String_createJavaStringFromNTS(NameStr(nspStruct->nspname));
ReleaseSysCache(nspTup);
return schemaName;
}
/*
* This checks specifically for a "Java-based scalar" a/k/a BaseUDT,
* and will call UDT_registerUDT accordingly if it is.
*/
Type Function_checkTypeBaseUDT(Oid typeId, Form_pg_type typeStruct)
{
HeapTuple procTup;
Datum d;
Form_pg_proc procStruct;
Type t = NULL;
jstring schemaName;
jclass clazz = NULL;
jclass t_clazz = NULL;
Oid procId[4] =
{
typeStruct->typinput, typeStruct->typreceive,
typeStruct->typsend, typeStruct->typoutput
};
jmethodID getter[4] =
{
s_Function_udtParseHandle, s_Function_udtReadHandle,
s_Function_udtWriteHandle, s_Function_udtToStringHandle
};
char *langName[4] = { NULL, NULL, NULL, NULL };
bool trusted[4];
jobject handle[4] = { NULL, NULL, NULL, NULL };
int i;
for ( i = 0; i < 4; ++ i )
{
if ( ! InstallHelper_isPLJavaFunction(
procId[i], &langName[i], &trusted[i]) )
break;
}
/*
* If that loop did not find all four support functions to be PL/Java ones,
* we have struck out; pfree anything it did find and return the bad news.
*/
if ( i < 4 )
{
for ( ; i >= 0 ; -- i )
if ( NULL != langName[i] )
pfree(langName[i]);
return NULL;
}
/*
* At this point, it is looking like a PL/Java BaseUDT; we have the four
* support function oids and the language names and trusted flags to go
* with them.
*
* Must still confirm that (1) each one is declared with a UDT[classname]
* style of AS string (getClassIfUDT returns null if not), (2) the named
* class inherits from SQLData (ClassCastException happens if not), and
* (3) that's the same class for all four of them (bail from this loop
* and goto classMismatch if not). We'll also consider it a classMismatch
* if some but not all getClassIfUDT results are null.
*
* Provided none of that goes wrong, obtain their handles in this loop too.
*/
for ( i = 0; i < 4; ++ i )
{
/*
* Get the pg_proc info corresponding to support function i,
* needed by getClassIfUDT().
*/
procTup = PgObject_getValidTuple(PROCOID, procId[i], "function");
procStruct = (Form_pg_proc)GETSTRUCT(procTup);
schemaName = getSchemaName(procStruct->pronamespace);
d = heap_copy_tuple_as_datum(
procTup, Type_getTupleDesc(s_pgproc_Type, 0));
t_clazz = (jclass)JNI_callStaticObjectMethod(s_Function_class,
s_Function_getClassIfUDT, Type_coerceDatum(s_pgproc_Type, d),
schemaName);
pfree((void *)d);
JNI_deleteLocalRef(schemaName);
ReleaseSysCache(procTup);
/*
* Save the first clazz returned; for subsequent ones, just confirm it's
* not different, then delete the extra local ref.
*/
if ( 0 == i )
clazz = t_clazz;
else
{
if ( JNI_FALSE == JNI_isSameObject(clazz, t_clazz) )
goto classMismatch;
JNI_deleteLocalRef(t_clazz);
}
if ( NULL == clazz )
continue;
handle[i] = obtainUDTHandle(getter[i], clazz, langName[i], trusted[i]);
}
/*
* We can only be here if getClassIfUDT returned the same value for clazz
* all four times. But that value could have been NULL; no UDT if so.
*/
if ( NULL != clazz )
t = (Type)UDT_registerUDT(clazz, typeId, typeStruct, 0, true,
handle[0], handle[1], handle[2], handle[3]);
/*
* UDT_registerUDT will already have called JNI_deleteLocalRef on the
* four handles. (Or clazz was NULL and there aren't any to delete anyway.)
*/
JNI_deleteLocalRef(clazz);
for ( i = 0; i < 4; ++ i )
pfree(langName[i]);
return t;
classMismatch:
while ( i --> 0 )
JNI_deleteLocalRef(handle[i]);
for ( i = 0; i < 4; ++ i )
pfree(langName[i]);
JNI_deleteLocalRef(clazz);
JNI_deleteLocalRef(t_clazz);
ereport(ERROR, (errmsg(
"PL/Java UDT with oid %u declares input/output/send/recv functions "
"in more than one class", typeId)));
pg_unreachable(); /* MSVC otherwise is not convinced */
}
static Function Function_create(
Oid funcOid, bool trusted, bool forTrigger,
bool forValidator, bool checkBody)
{
Function self;
HeapTuple procTup =
PgObject_getValidTuple(PROCOID, funcOid, "function");
Form_pg_proc procStruct = (Form_pg_proc)GETSTRUCT(procTup);
HeapTuple lngTup =
PgObject_getValidTuple(LANGOID, procStruct->prolang, "language");
Form_pg_language lngStruct = (Form_pg_language)GETSTRUCT(lngTup);
jstring lname = String_createJavaStringFromNTS(NameStr(lngStruct->lanname));
bool ltrust = lngStruct->lanpltrusted;
jstring schemaName;
Ptr2Long p2l;
Datum d;
jobject invocable;
if ( trusted != ltrust )
elog(ERROR,
"function with oid %u invoked through wrong call handler "
"for %strusted language %s", funcOid, ltrust ? "" : "un",
NameStr(lngStruct->lanname));
d = heap_copy_tuple_as_datum(procTup, Type_getTupleDesc(s_pgproc_Type, 0));
schemaName = getSchemaName(procStruct->pronamespace);
self = /* will rely on the fact that allocInstance zeroes memory */
(Function)PgObjectClass_allocInstance(s_FunctionClass,TopMemoryContext);
p2l.longVal = 0;
p2l.ptrVal = (void *)self;
PG_TRY();
{
invocable =
JNI_callStaticObjectMethod(s_Function_class, s_Function_create,
p2l.longVal, Type_coerceDatum(s_pgproc_Type, d), lname,
schemaName,
trusted ? JNI_TRUE : JNI_FALSE,
forTrigger ? JNI_TRUE : JNI_FALSE,
forValidator ? JNI_TRUE : JNI_FALSE,
checkBody ? JNI_TRUE : JNI_FALSE);
}
PG_CATCH();
{
JNI_deleteLocalRef(schemaName);
ReleaseSysCache(lngTup);
ReleaseSysCache(procTup);
pfree(self); /* would otherwise leak into TopMemoryContext */
PG_RE_THROW();
}
PG_END_TRY();
JNI_deleteLocalRef(schemaName);
ReleaseSysCache(lngTup);
ReleaseSysCache(procTup);
/*
* One of four things has happened, the product of two binary choices:
* - This Function turns out to be either a UDT function, or a nonUDT one.
* - it is now fully initialized and should be returned, or it isn't, and
* should be pfree()d. (Validator calls don't have to do the whole job.)
*
* If Function.create returned a non-NULL result, this is a fully
* initialized, non-UDT function, ready to save and use. (That can happen
* even during validation; if checkBody is true, enough work is done to get
* a complete result, so we might as well save it.)
*
* If it returned NULL, this is either an incompletely-initialized non-UDT
* function, or it is a UDT function (whether fully initialized or not; it
* is always NULL for a UDT function). If it is a UDT function and not
* complete, it should be pfree()d. If complete, it has already been
* registered with the UDT machinery and should be saved. We can arrange
* (see _storeToUDT below) for the isUDT flag to be left false if the UDT
* initialization isn't complete; that collapses the need-to-pfree cases
* into one case here (Function.create returned NULL && ! isUDT).
*
* Because allocInstance zeroes memory, isUDT is reliably false even if
* the Java code bailed early.
*/
if ( NULL != invocable )
{
self->func.nonudt.invocable = JNI_newGlobalRef(invocable);
JNI_deleteLocalRef(invocable);
}
else if ( ! self->isUDT )
{
pfree(self);
if ( forValidator )
return NULL;
elog(ERROR,
"failed to create a PL/Java function (oid %u) and not validating",
funcOid);
}
return self;
}
/*
* Get a Function using a function Oid. If the function is not found, one
* will be created based on the class and method name denoted in the "AS"
* clause, the parameter types, and the return value of the function
* description. If "forTrigger" is true, the parameter type and
* return value of the function will be fixed to:
* void <method name>(org.postgresql.pljava.TriggerData td)
*
* If forValidator is true, forTrigger is disregarded, and will be determined
* from the function's pg_proc entry. If forValidator is false, checkBody has no
* meaning.
*
* If called with forValidator true, may return NULL. The validator doesn't
* use the result.
*
* In all other cases, this Function has been stored
* in currentInvocation->function upon successful return from here.
*/
static inline Function
getFunction(
Oid funcOid, bool trusted, bool forTrigger,
bool forValidator, bool checkBody)
{
Function func =
forValidator ? NULL : (Function)HashMap_getByOid(s_funcMap, funcOid);
if ( NULL == func )
{
func = Function_create(
funcOid, trusted, forTrigger, forValidator, checkBody);
if ( NULL != func )
HashMap_putByOid(s_funcMap, funcOid, func);
}
currentInvocation->function = func;
return func;
}
jobject Function_getTypeMap(Function self)
{
return self->func.nonudt.typeMap;
}
static bool Function_inUse(Function func)
{
Invocation* ic = currentInvocation;
while(ic != 0)
{
if(ic->function == func)
return true;
ic = ic->previous;
}
return false;
}
void Function_clearFunctionCache(void)
{
Entry entry;
HashMap oldMap = s_funcMap;
Iterator itor = Iterator_create(oldMap);
s_funcMap = HashMap_create(59, TopMemoryContext);
while((entry = Iterator_next(itor)) != 0)
{
Function func = (Function)Entry_getValue(entry);
if(func != 0)
{
if(Function_inUse(func))
{
/* This is the replace_jar function or similar. Just
* move it to the new map.
*/
HashMap_put(s_funcMap, Entry_getKey(entry), func);
}
else
{
Entry_setValue(entry, 0);
PgObject_free((PgObject)func);
}
}
}
PgObject_free((PgObject)itor);
PgObject_free((PgObject)oldMap);
}
/*
* Type_isPrimitive() by itself returns true for both, say, int and int[].
* That is sometimes relied on, as in the code that would accept Integer[]
* as a replacement for int[].
*
* However, it isn't correct for determining whether the thing should be passed
* to Java as a primitive or a reference, because of course no Java array is a
* primitive. Hence this method, which requires both Type_isPrimitive to be true
* and that the type is not an array.
*/
static inline bool
passAsPrimitive(Type t)
{
return Type_isPrimitive(t) && (NULL == Type_getElementType(t));
}
Datum
Function_invoke(
Oid funcoid, bool trusted, bool forTrigger, bool forValidator,
bool checkBody, PG_FUNCTION_ARGS)
{
Function self;
Datum retVal;
Size passedArgCount;
Type invokerType;
bool skipParameterConversion = false;
self = getFunction(funcoid, trusted, forTrigger, forValidator, checkBody);
if ( forValidator )
PG_RETURN_VOID();
if ( forTrigger )
return invokeTrigger(self, fcinfo);
fcinfo->isnull = false;
if(self->isUDT)
return self->func.udt.udtFunction(self->func.udt.udt, fcinfo);
if ( self->func.nonudt.isMultiCall )
{
if ( SRF_IS_FIRSTCALL() )
{
/* A class loader or other mechanism might have connected already.
* This connection must be dropped since its parent context
* is wrong.
*/
Invocation_assertDisconnect();
}
else
{
/* In PL/Java's implementation of the ValuePerCall SRF protocol, the
* passed parameters from SQL only matter on the first call. All
* subsequent calls are either hasNext()/next() on an Iterator, or
* assignRowValues on a ResultSetProvider, and none of those methods
* will receive the SQL-passed parameters. So there is no need to
* spend cycles to convert them and populate the parameter area.
*/
skipParameterConversion = true;
}
}
passedArgCount = PG_NARGS();
if ( ! skipParameterConversion )
{
jsize reservedArgCount = reserveParameterFrame(
self->func.nonudt.numRefParams, self->func.nonudt.numPrimParams);
if ( passedArgCount != reservedArgCount
&& passedArgCount + 1 != reservedArgCount ) /* the OUT arg case */
elog(ERROR, "function expecting %u arguments passed %u",
(unsigned int)reservedArgCount, (unsigned int)passedArgCount);
}
installContextLoader(self);
invokerType = self->func.nonudt.returnType;
if ( passedArgCount > 0 && ! skipParameterConversion )
{
int32 idx;
int32 refIdx = 0;
int32 primIdx = 0;
Type* types = self->func.nonudt.paramTypes;
jvalue coerced;
if(Type_isDynamic(invokerType))
invokerType = Type_getRealType(invokerType,
get_fn_expr_rettype(fcinfo->flinfo), self->func.nonudt.typeMap);
for(idx = 0; idx < passedArgCount; ++idx)
{
Type paramType = types[idx];
bool passPrimitive = passAsPrimitive(paramType);
if(PG_ARGISNULL(idx))
{
/*
* Set this argument to zero (or null in case of object)
*/
if ( passPrimitive )
s_primitiveParameters[primIdx++].j = 0L;
else
++ refIdx; /* array element is already initially null */
}
else
{
if(Type_isDynamic(paramType))
paramType = Type_getRealType(paramType,
get_fn_expr_argtype(fcinfo->flinfo, idx),
self->func.nonudt.typeMap);
coerced = Type_coerceDatum(paramType, PG_GETARG_DATUM(idx));
if ( passPrimitive )
s_primitiveParameters[primIdx++] = coerced;
else