-
Notifications
You must be signed in to change notification settings - Fork 76
/
DDRProcessor.java
1474 lines (1315 loc) · 42.2 KB
/
DDRProcessor.java
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-2013 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:
* Tada AB
* Purdue University
*/
package org.postgresql.pljava.sqlgen;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.ResultSet;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.Set;
import java.util.regex.Pattern;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import static javax.lang.model.util.ElementFilter.methodsIn;
import static javax.tools.Diagnostic.Kind;
import org.postgresql.pljava.ResultSetHandle;
import org.postgresql.pljava.ResultSetProvider;
import org.postgresql.pljava.TriggerData;
import org.postgresql.pljava.annotation.Function;
import org.postgresql.pljava.annotation.SQLAction;
import org.postgresql.pljava.annotation.SQLActions;
import org.postgresql.pljava.annotation.SQLType;
import org.postgresql.pljava.annotation.Trigger;
/**
* Annotation processor invoked by the annotations framework in javac for
* annotations of type org.postgresql.pljava.annotation.*.
*
* Simply forwards to a DDRProcessorImpl instance that is not constructed
* until the framework calls init (since there is nothing useful for the
* constructor to do until then).
*
* @author Thomas Hallgren - pre-Java6 version
* @author Chapman Flack (Purdue Mathematics) - update to Java6,
* add SQLType/SQLAction, polishing
*/
@SupportedAnnotationTypes({"org.postgresql.pljava.annotation.*"})
@SupportedOptions
({
"ddr.name.trusted", // default "java"
"ddr.name.untrusted", // default "javaU"
"ddr.output" // name of ddr file to write
})
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class DDRProcessor extends AbstractProcessor
{
private DDRProcessorImpl impl;
@Override
public void init( ProcessingEnvironment processingEnv)
{
super.init( processingEnv);
impl = new DDRProcessorImpl( processingEnv);
}
@Override
public boolean process( Set<? extends TypeElement> tes, RoundEnvironment re)
{
if ( null == impl )
throw new IllegalStateException(
"The annotation processing framework has called process() " +
"before init()");
return impl.process( tes, re);
}
}
/**
* Where the work happens.
*/
class DDRProcessorImpl
{
// Things supplied by the calling framework in ProcessingEnvironment,
// used enough that it makes sense to break them out here with
// short names that all nested classes below will inherit.
//
final Elements elmu;
final Filer filr;
final Locale loca;
final Messager msgr;
final Map<String, String> opts;
final SourceVersion srcv;
final Types typu;
// Similarly, the TypeMapper should be easily available to code below.
//
final TypeMapper tmpr;
// Options obtained from the invocation
//
final String nameTrusted;
final String nameUntrusted;
final String output;
// Certain known types that need to be recognized in the processed code
//
final DeclaredType TY_ITERATOR;
final DeclaredType TY_RESULTSET;
final DeclaredType TY_RESULTSETPROVIDER;
final DeclaredType TY_RESULTSETHANDLE;
final DeclaredType TY_TRIGGERDATA;
// Our own annotations
//
final TypeElement AN_FUNCTION;
final TypeElement AN_SQLACTION;
final TypeElement AN_SQLACTIONS;
final TypeElement AN_SQLTYPE;
final TypeElement AN_TRIGGER;
DDRProcessorImpl( ProcessingEnvironment processingEnv)
{
elmu = processingEnv.getElementUtils();
filr = processingEnv.getFiler();
loca = processingEnv.getLocale();
msgr = processingEnv.getMessager();
opts = processingEnv.getOptions();
srcv = processingEnv.getSourceVersion();
typu = processingEnv.getTypeUtils();
tmpr = new TypeMapper();
String optv;
optv = opts.get( "ddr.name.trusted");
if ( null != optv )
nameTrusted = optv;
else
nameTrusted = "java";
optv = opts.get( "ddr.name.untrusted");
if ( null != optv )
nameUntrusted = optv;
else
nameUntrusted = "javaU";
optv = opts.get( "ddr.output");
if ( null != optv )
output = optv;
else
output = "pljava.ddr";
TY_ITERATOR = typu.getDeclaredType(
elmu.getTypeElement( java.util.Iterator.class.getName()));
TY_RESULTSET = typu.getDeclaredType(
elmu.getTypeElement( java.sql.ResultSet.class.getName()));
TY_RESULTSETPROVIDER = typu.getDeclaredType(
elmu.getTypeElement( ResultSetProvider.class.getName()));
TY_RESULTSETHANDLE = typu.getDeclaredType(
elmu.getTypeElement( ResultSetHandle.class.getName()));
TY_TRIGGERDATA = typu.getDeclaredType(
elmu.getTypeElement( TriggerData.class.getName()));
AN_FUNCTION = elmu.getTypeElement( Function.class.getName());
AN_SQLACTION = elmu.getTypeElement( SQLAction.class.getName());
AN_SQLACTIONS = elmu.getTypeElement( SQLActions.class.getName());
AN_SQLTYPE = elmu.getTypeElement( SQLType.class.getName());
AN_TRIGGER = elmu.getTypeElement( Trigger.class.getName());
}
void msg( Kind kind, String fmt, Object... args)
{
msgr.printMessage( kind, String.format( fmt, args));
}
void msg( Kind kind, Element e, String fmt, Object... args)
{
msgr.printMessage( kind, String.format( fmt, args), e);
}
void msg( Kind kind, Element e, AnnotationMirror a,
String fmt, Object... args)
{
msgr.printMessage( kind, String.format( fmt, args), e, a);
}
void msg( Kind kind, Element e, AnnotationMirror a, AnnotationValue v,
String fmt, Object... args)
{
msgr.printMessage( kind, String.format( fmt, args), e, a, v);
}
/**
* Collection of code snippets being accumulated (possibly over more than
* one round), keyed by the object for which each snippet has been
* generated.
*/
Map<Object, Snippet> snippets = new HashMap<Object, Snippet>();
/**
* Find the elements in each round that carry any of the annotations of
* interest and generate code snippets accordingly. On the last round, with
* all processing complete, generate the deployment descriptor file.
*/
boolean process( Set<? extends TypeElement> tes, RoundEnvironment re)
{
boolean functionPresent = false;
boolean sqlActionPresent = false;
boolean sqlActionsPresent = false;
boolean willClaim = true;
for ( TypeElement te : tes )
{
if ( AN_FUNCTION.equals( te) )
functionPresent = true;
else if ( AN_SQLACTION.equals( te) )
sqlActionPresent = true;
else if ( AN_SQLACTIONS.equals( te) )
sqlActionsPresent = true;
else if ( AN_SQLTYPE.equals( te) )
; // these are handled within FunctionImpl
else
{
msg( Kind.WARNING, te,
"pljava annotation processor version may be older than " +
"this annotation:\n%s", te.toString());
willClaim = false;
}
}
if ( functionPresent )
for ( Element e : re.getElementsAnnotatedWith( AN_FUNCTION) )
processFunction( e);
if ( sqlActionPresent )
for ( Element e : re.getElementsAnnotatedWith( AN_SQLACTION) )
processSQLAction( e);
if ( sqlActionsPresent )
for ( Element e : re.getElementsAnnotatedWith( AN_SQLACTIONS) )
processSQLActions( e);
if ( re.processingOver() && ! re.errorRaised() )
generateDescriptor();
return willClaim;
}
/**
* Arrange the collected snippets into a workable sequence (nothing with
* requires="X" can come before whatever has provides="X"), then create
* a deployment descriptor file in proper form.
*/
void generateDescriptor()
{
List<Vertex<Snippet>> vs =
new ArrayList<Vertex<Snippet>>( snippets.size());
Map<String, Vertex<Snippet>> provider =
new HashMap<String, Vertex<Snippet>>();
Set<String> consumer = new HashSet<String>();
boolean errorRaised = false;
for ( Snippet snip : snippets.values() )
{
snip.characterize();
Vertex<Snippet> v = new Vertex<Snippet>( snip);
vs.add( v);
for ( String s : snip.provides() )
if ( null != provider.put( s, v) )
{
msg( Kind.ERROR, "tag %s has more than one provider", s);
errorRaised = true;
}
for ( String s : snip.requires() )
consumer.add( s);
}
consumer.removeAll( provider.keySet());
for ( String s : consumer )
{
msg( Kind.ERROR, "tag \"%s\" is required but nowhere provided", s);
errorRaised = true;
}
if ( errorRaised )
return;
for ( Vertex<Snippet> v : vs )
for ( String s : v.payload.requires() )
provider.get( s).precede( v);
Queue<Vertex<Snippet>> q = new LinkedList<Vertex<Snippet>>();
for ( Vertex<Snippet> v : vs )
if ( 0 == v.indegree )
q.add( v);
Snippet[] snips = new Snippet [ vs.size() ];
for ( int i = 0 ; i < snips.length ; ++ i )
{
Vertex<Snippet> v = q.remove();
snips[i] = v.payload;
v.use( q);
}
try
{
DDRWriter.emit( snips, this);
}
catch ( IOException ioe )
{
msg( Kind.ERROR, "while writing %s: %s", output, ioe.getMessage());
}
}
/**
* Process a single element annotated with @SQLAction.
*/
void processSQLAction( Element e)
{
SQLActionImpl sa = (SQLActionImpl)snippets.get( e);
if ( null == sa )
{
sa = new SQLActionImpl();
snippets.put( e, sa);
}
for ( AnnotationMirror am : elmu.getAllAnnotationMirrors( e) )
{
if ( am.getAnnotationType().asElement().equals( AN_SQLACTION) )
populateAnnotationImpl( sa, e, am);
}
}
/**
* Process a single element annotated with @SQLActions (which simply takes
* an array of @SQLAction as a way to associate more than one SQLAction with
* a single program element)..
*/
void processSQLActions( Element e)
{
for ( AnnotationMirror am : elmu.getAllAnnotationMirrors( e) )
{
if ( am.getAnnotationType().asElement().equals( AN_SQLACTIONS) )
{
SQLActionsImpl sas = new SQLActionsImpl();
populateAnnotationImpl( sas, e, am);
for ( SQLAction sa : sas.value() )
snippets.put( sa, (Snippet)sa);
}
}
}
/**
* Process a single element annotated with @Function. After checking that
* it has the right modifiers to be called via pljava, analyze its type
* information and annotations and register an appropriate SQL code snippet.
*/
void processFunction( Element e)
{
Set<Modifier> mods = e.getModifiers();
if ( ! mods.contains( Modifier.PUBLIC) )
{
msg( Kind.ERROR, e, "A pljava function must be public");
}
if ( ! mods.contains( Modifier.STATIC) )
{
msg( Kind.ERROR, e, "A pljava function must be static");
}
for ( Element ee = e; null != ( ee = ee.getEnclosingElement() ); )
{
if ( ElementKind.CLASS.equals( ee.getKind()) )
{
if ( ! ee.getModifiers().contains( Modifier.PUBLIC) )
msg( Kind.ERROR, ee,
"A pljava function must not have a non-public " +
"enclosing class");
if ( ((TypeElement)ee).getNestingKind().equals(
NestingKind.TOP_LEVEL) )
break;
}
}
FunctionImpl f = (FunctionImpl)snippets.get( e);
if ( null == f )
{
f = new FunctionImpl( (ExecutableElement)e);
snippets.put( e, f);
}
for ( AnnotationMirror am : elmu.getAllAnnotationMirrors( e) )
{
if ( am.getAnnotationType().asElement().equals( AN_FUNCTION) )
populateAnnotationImpl( f, e, am);
}
}
/**
* Abstract superclass for synthetic implementations of annotation
* interfaces; these can be populated with element-value pairs from
* an AnnotationMirror and then used in the natural way for access to
* the values. Each subclass of this should implement the intended
* annotation interface, and should also have a
* setFoo(Object,boolean,Element) method for each foo() method in the
* interface. Rather than longwindedly using the type system to enforce
* that the needed setter methods are all there, they will be looked
* up using reflection.
*/
class AbstractAnnotationImpl implements Annotation
{
public Class<? extends Annotation> annotationType()
{
throw new UnsupportedOperationException();
}
/**
* Populate an array of specified type from an annotation value
* representing an array.
*
* AnnotationValue's getValue() method returns Object, where the
* object is known to be an instance of one of a small set of classes.
* Populating an array when that value represents one is a common
* operation, so it is factored out here.
*/
<T> T[] avToArray( Object o, Class<T> k)
{
@SuppressWarnings({"unchecked"})
List<? extends AnnotationValue> vs =
(List<? extends AnnotationValue>)o;
@SuppressWarnings({"unchecked"})
T[] a = (T[])Array.newInstance( k, vs.size());
int i = 0;
for ( AnnotationValue av : vs )
a[i++] = k.cast(av.getValue());
return a;
}
}
/**
* Populate an AbstractAnnotationImpl-derived Annotation implementation
* from the element-value pairs in an AnnotationMirror. For each element
* foo in the annotation interface, the implementation is assumed to have
* a method setFoo(Object o, boolean explicit, element e) where o is the
* element's value as obtained from AnnotationValue.getValue(), explicit
* indicates whether the element was explicitly present in the annotation
* or filled in from a default value, and e is the element carrying the
* annotation (chiefly for use as a location hint in diagnostic messages).
*
* Some of the annotation implementations below will leave certain elements
* null if they were not given explicit values, in order to have a clear
* indication that they were defaulted, even though that is not the way
* normal annotation objects behave.
*/
void populateAnnotationImpl(
AbstractAnnotationImpl inst, Element e, AnnotationMirror am)
{
Map<? extends ExecutableElement, ? extends AnnotationValue> explicit =
am.getElementValues();
Map<? extends ExecutableElement, ? extends AnnotationValue> defaulted =
elmu.getElementValuesWithDefaults( am);
// Astonishingly, even though JLS3 9.7 clearly says "annotations must
// contain an element-value pair for every element of the corresponding
// annotation type, except for those elements with default values, or a
// compile-time error occurs" - in Sun 1.6.0_39 javac never flags
// the promised error, and instead allows us to NPE on something that
// ought to be guaranteed to be there! >:[
//
// If you want something done right, you have to do it yourself....
//
Element anne = am.getAnnotationType().asElement();
List<ExecutableElement> keys = methodsIn( anne.getEnclosedElements());
for ( ExecutableElement k : keys )
if ( ! defaulted.containsKey( k) )
msg( Kind.ERROR, e, am,
"annotation missing required element \"%s\"",
k.getSimpleName());
for (
Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> me
: defaulted.entrySet()
)
{
ExecutableElement k = me.getKey();
AnnotationValue av = me.getValue();
boolean isExplicit = explicit.containsKey( k);
String name = k.getSimpleName().toString();
Object v = av.getValue();
Class<? extends Annotation> kl = inst.getClass();
try
{
kl.getMethod( // let setter for foo() be setFoo()
"set"+name.substring( 0, 1).toUpperCase() +
name.substring( 1),
Object.class, boolean.class, Element.class)
.invoke(inst, v, isExplicit, e);
}
catch (NoSuchMethodException nsme)
{
// could use this space to look for a _foo field and set it in
// the obvious way, eliminating the need for all the setter
// methods that do nothing but set the field in the obvious way.
//
throw new RuntimeException(
"Incomplete implementation in annotation processor", nsme);
}
catch (IllegalAccessException iae)
{
throw new RuntimeException(
"Incorrect implementation of annotation processor", iae);
}
catch (InvocationTargetException ite)
{
String msg = ite.getCause().getMessage();
msg( Kind.ERROR, e, am, av, "%s", msg);
}
}
}
// It could be nice to have another annotation-driven tool that could just
// generate these implementations of some annotation types....
class SQLTypeImpl extends AbstractAnnotationImpl implements SQLType
{
public String value() { return _value; }
public String[] defaultValue() { return _defaultValue; }
String _value;
String[] _defaultValue;
public void setValue( Object o, boolean explicit, Element e)
{
if ( explicit )
_value = (String)o;
}
public void setDefaultValue( Object o, boolean explicit, Element e)
{
if ( explicit )
_defaultValue = avToArray( o, String.class);
}
}
class SQLActionsImpl extends AbstractAnnotationImpl implements SQLActions
{
public SQLAction[] value() { return _value; }
SQLAction[] _value;
public void setValue( Object o, boolean explicit, Element e)
{
AnnotationMirror[] ams = avToArray( o, AnnotationMirror.class);
_value = new SQLAction [ ams.length ];
int i = 0;
for ( AnnotationMirror am : ams )
{
SQLActionImpl a = new SQLActionImpl();
populateAnnotationImpl( a, e, am);
_value [ i++ ] = a;
}
}
}
class SQLActionImpl
extends AbstractAnnotationImpl
implements SQLAction, Snippet
{
public String[] install() { return _install; }
public String[] remove() { return _remove; }
public String[] provides() { return _provides; }
public String[] requires() { return _requires; }
public String[] deployStrings() { return _install; }
public String[] undeployStrings() { return _remove; }
public void characterize() { }
String[] _install;
String[] _remove;
String[] _provides;
String[] _requires;
public void setInstall( Object o, boolean explicit, Element e)
{
_install = avToArray( o, String.class);
}
public void setRemove( Object o, boolean explicit, Element e)
{
_remove = avToArray( o, String.class);
}
public void setProvides( Object o, boolean explicit, Element e)
{
_provides = avToArray( o, String.class);
}
public void setRequires( Object o, boolean explicit, Element e)
{
_requires = avToArray( o, String.class);
}
}
class TriggerImpl
extends AbstractAnnotationImpl
implements Trigger, Snippet
{
public String[] arguments() { return _arguments; }
public Event[] events() { return _events; }
public String name() { return _name; }
public String schema() { return _schema; }
public String table() { return _table; }
public Scope scope() { return _scope; }
public When when() { return _when; }
public String[] provides() { return new String[0]; }
public String[] requires() { return new String[0]; }
String[] _arguments;
Event[] _events;
String _name;
String _schema;
String _table;
Scope _scope;
When _when;
FunctionImpl func;
AnnotationMirror origin;
TriggerImpl( FunctionImpl f, AnnotationMirror am)
{
func = f;
origin = am;
}
public void setArguments( Object o, boolean explicit, Element e)
{
_arguments = avToArray( o, String.class);
}
public void setEvents( Object o, boolean explicit, Element e)
{
VariableElement[] ves = avToArray( o, VariableElement.class);
_events = new Event [ ves.length ];
int i = 0;
for ( VariableElement ve : ves )
_events[i++] = Event.valueOf( ve.getSimpleName().toString());
}
public void setName( Object o, boolean explicit, Element e)
{
if ( explicit )
_name = (String)o;
}
public void setSchema( Object o, boolean explicit, Element e)
{
_schema = (String)o;
}
public void setTable( Object o, boolean explicit, Element e)
{
_table = (String)o;
}
public void setScope( Object o, boolean explicit, Element e)
{
_scope =
Scope.valueOf( ((VariableElement)o).getSimpleName().toString());
}
public void setWhen( Object o, boolean explicit, Element e)
{
_when =
When.valueOf( ((VariableElement)o).getSimpleName().toString());
}
public void characterize()
{
if ( Scope.ROW.equals( _scope) )
for ( Event e : _events )
if ( Event.TRUNCATE.equals( e) )
msg( Kind.ERROR, func.func, origin,
"TRUNCATE trigger cannot be FOR EACH ROW");
if ( null == _name )
_name = TriggerNamer.synthesizeName( this);
}
public String[] deployStrings()
{
StringBuilder sb = new StringBuilder();
sb.append( "CREATE TRIGGER ").append( name()).append( "\n\t");
sb.append( when().toString()).append( ' ');
int s = _events.length;
for ( Event e : _events )
{
sb.append( e.toString());
if ( 0 < -- s )
sb.append( " OR ");
}
sb.append( "\n\tON ");
if ( ! "".equals( schema()) )
sb.append( schema()).append( '.');
sb.append( table()).append( "\n\tFOR EACH ");
sb.append( scope().toString()).append( "\n\tEXECUTE PROCEDURE ");
String n = func.nameAndParams( false);
n = n.substring( 0, n.length() - 1); // drop closing )
sb.append( n);
s = _arguments.length;
for ( String a : _arguments )
{
sb.append( "\n\t").append( DDRWriter.eQuote( a));
if ( 0 < -- s )
sb.append( ',');
}
sb.append( ')');
return new String[] { sb.toString() };
}
public String[] undeployStrings()
{
StringBuilder sb = new StringBuilder();
sb.append( "DROP TRIGGER ").append( name()).append( "\n\tON ");
if ( ! "".equals( schema()) )
sb.append( schema()).append( '.');
sb.append( table());
return new String[] { sb.toString() };
}
}
class FunctionImpl
extends AbstractAnnotationImpl
implements Function, Snippet
{
public String complexType() { return _complexType; }
public String name() { return _name; }
public String schema() { return _schema; }
public OnNullInput onNullInput() { return _onNullInput; }
public Security security() { return _security; }
public Type type() { return _type; }
public Trust trust() { return _trust; }
public boolean leakproof() { return _leakproof; }
public int cost() { return _cost; }
public int rows() { return _rows; }
public String[] settings() { return _settings; }
public String[] provides() { return _provides; }
public String[] requires() { return _requires; }
public Trigger[] triggers() { return _triggers; }
ExecutableElement func;
String _complexType;
String _name;
String _schema;
OnNullInput _onNullInput;
Security _security;
Type _type;
Trust _trust;
boolean _leakproof;
int _cost;
int _rows;
String[] _settings;
String[] _provides;
String[] _requires;
Trigger[] _triggers;
boolean complexViaInOut = false;
boolean setof = false;
TypeMirror setofComponent = null;
boolean trigger = false;
FunctionImpl(ExecutableElement e)
{
func = e;
}
public void setComplexType( Object o, boolean explicit, Element e)
{
_complexType = (String)o;
}
public void setName( Object o, boolean explicit, Element e)
{
_name = (String)o;
if ( "".equals( _name) )
_name = func.getSimpleName().toString();
}
public void setSchema( Object o, boolean explicit, Element e)
{
_schema = (String)o;
}
public void setOnNullInput( Object o, boolean explicit, Element e)
{
_onNullInput =
OnNullInput.valueOf( ((VariableElement)o).getSimpleName()
.toString());
}
public void setSecurity( Object o, boolean explicit, Element e)
{
_security =
Security.valueOf( ((VariableElement)o).getSimpleName()
.toString());
}
public void setType( Object o, boolean explicit, Element e)
{
_type =
Type.valueOf( ((VariableElement)o).getSimpleName().toString());
}
public void setTrust( Object o, boolean explicit, Element e)
{
_trust =
Trust.valueOf( ((VariableElement)o).getSimpleName().toString());
}
public void setLeakproof( Object o, boolean explicit, Element e)
{
_leakproof = ((Boolean)o).booleanValue();
}
public void setCost( Object o, boolean explicit, Element e)
{
_cost = ((Integer)o).intValue();
if ( _cost < 0 && explicit )
throw new IllegalArgumentException( "cost must be nonnegative");
}
public void setRows( Object o, boolean explicit, Element e)
{
_rows = ((Integer)o).intValue();
if ( _rows < 0 && explicit )
throw new IllegalArgumentException( "rows must be nonnegative");
}
public void setSettings( Object o, boolean explicit, Element e)
{
_settings = avToArray( o, String.class);
}
public void setProvides( Object o, boolean explicit, Element e)
{
_provides = avToArray( o, String.class);
}
public void setRequires( Object o, boolean explicit, Element e)
{
_requires = avToArray( o, String.class);
}
public void setTriggers( Object o, boolean explicit, Element e)
{
AnnotationMirror[] ams = avToArray( o, AnnotationMirror.class);
_triggers = new Trigger [ ams.length ];
int i = 0;
for ( AnnotationMirror am : ams )
{
TriggerImpl ti = new TriggerImpl( this, am);
populateAnnotationImpl( ti, e, am);
_triggers [ i++ ] = ti;
}
}
public void characterize()
{
TypeMirror ret = func.getReturnType();
if ( ret.getKind().equals( TypeKind.ERROR) ) {
msg( Kind.ERROR, func,
"Unable to resolve return type of function");
return;
}
ExecutableType et = (ExecutableType)func.asType();
List<? extends TypeMirror> ptms = et.getParameterTypes();
int arity = ptms.size();
if ( ! "".equals( complexType())
&& ret.getKind().equals( TypeKind.BOOLEAN) )
{
complexViaInOut = true;
TypeMirror tm = ptms.get( arity - 1);
if ( tm.getKind().equals( TypeKind.ERROR)
// unresolved things seem assignable to anything
|| ! typu.isSameType( tm, TY_RESULTSET) )
{
msg( Kind.ERROR, func.getParameters().get( arity - 1),
"Last parameter of complex-type-returning function " +
"must be ResultSet");
return;
}
}
else if ( typu.isAssignable( typu.erasure( ret), TY_ITERATOR) )
{
setof = true;
List<TypeMirror> pending = new LinkedList<TypeMirror>();
pending.add( ret);
while ( ! pending.isEmpty() )
{
TypeMirror tm = pending.remove( 0);
if ( typu.isSameType( typu.erasure( tm), TY_ITERATOR) )
{
DeclaredType dt = (DeclaredType)tm;
List<? extends TypeMirror> typeArgs =
dt.getTypeArguments();
if ( 1 != typeArgs.size() )
{
msg( Kind.ERROR, func,
"Need one type argument for Iterator " +
"return type");
return;
}
setofComponent = typeArgs.get( 0);
break;
}
else
{
pending.addAll( typu.directSupertypes( tm));
}
}
if ( null == setofComponent )
{
msg( Kind.ERROR, func,
"Failed to find setof component type");
return;
}
}
else if ( typu.isAssignable( ret, TY_RESULTSETPROVIDER)
|| typu.isAssignable( ret, TY_RESULTSETHANDLE) )
{
setof = true;
}
else if ( ret.getKind().equals( TypeKind.VOID) && 1 == arity )
{
TypeMirror tm = ptms.get( 0);
if ( ! tm.getKind().equals( TypeKind.ERROR)
// unresolved things seem assignable to anything
&& typu.isSameType( tm, TY_TRIGGERDATA) )
{
trigger = true;
}
}
if ( ! setof && -1 != rows() )
msg( Kind.ERROR, func,
"ROWS specified on a function not returning SETOF");
if ( ! trigger && 0 != _triggers.length )
msg( Kind.ERROR, func,