-
Notifications
You must be signed in to change notification settings - Fork 951
/
TransactionalTransform.groovy
265 lines (226 loc) · 12.7 KB
/
TransactionalTransform.groovy
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
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.transaction.transform
import static org.codehaus.groovy.grails.compiler.injection.GrailsASTUtils.*
import grails.transaction.Transactional
import groovy.transform.CompileStatic
import java.lang.reflect.Modifier
import org.codehaus.groovy.ast.*
import org.codehaus.groovy.ast.expr.*
import org.codehaus.groovy.ast.stmt.BlockStatement
import org.codehaus.groovy.ast.stmt.ExpressionStatement
import org.codehaus.groovy.ast.stmt.ReturnStatement
import org.codehaus.groovy.control.CompilePhase
import org.codehaus.groovy.control.SourceUnit
import org.codehaus.groovy.grails.compiler.injection.GrailsASTUtils
import org.codehaus.groovy.grails.compiler.injection.GrailsArtefactClassInjector
import org.codehaus.groovy.grails.orm.support.GrailsTransactionTemplate
import org.codehaus.groovy.grails.orm.support.TransactionManagerAware
import org.codehaus.groovy.syntax.Token
import org.codehaus.groovy.syntax.Types
import org.codehaus.groovy.transform.ASTTransformation
import org.codehaus.groovy.transform.GroovyASTTransformation
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.TransactionStatus
import org.springframework.transaction.interceptor.NoRollbackRuleAttribute
import org.springframework.transaction.interceptor.RollbackRuleAttribute
import org.springframework.transaction.interceptor.RuleBasedTransactionAttribute
/**
* This AST transform reads the {@link grails.transaction.Transactional} annotation and transforms method calls by
* wrapping the body of the method in an execution of {@link GrailsTransactionTemplate}.
*
*
* @author Graeme Rocher
* @since 2.3
*/
@CompileStatic
@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
class TransactionalTransform implements ASTTransformation{
public static final ClassNode MY_TYPE = new ClassNode(Transactional)
private static final String PROPERTY_TRANSACTION_MANAGER = "transactionManager"
private static final String METHOD_EXECUTE = "execute"
@Override
void visit(ASTNode[] astNodes, SourceUnit source) {
if (!(astNodes[0] instanceof AnnotationNode) || !(astNodes[1] instanceof AnnotatedNode)) {
throw new RuntimeException('Internal error: wrong types: $node.class / $parent.class')
}
AnnotatedNode parent = (AnnotatedNode) astNodes[1];
AnnotationNode annotationNode = (AnnotationNode) astNodes[0];
if (!MY_TYPE.equals(annotationNode.getClassNode())) {
return;
}
if (parent instanceof MethodNode) {
MethodNode methodNode = (MethodNode)parent
final declaringClassNode = methodNode.getDeclaringClass()
weaveTransactionManagerAware(source, declaringClassNode)
weaveTransactionalMethod(source, declaringClassNode, annotationNode, methodNode)
}
else if (parent instanceof ClassNode) {
weaveTransactionalBehavior(source, parent, annotationNode)
}
}
public void weaveTransactionalBehavior(SourceUnit source, ClassNode classNode, AnnotationNode annotationNode) {
weaveTransactionManagerAware(source, classNode)
ClassNode controllerMethodAnn = getAnnotationClassNode("grails.web.controllers.ControllerMethod")
List<MethodNode> methods = new ArrayList<MethodNode>(classNode.getMethods());
for (MethodNode md in methods) {
if (Modifier.isPublic(md.modifiers) && !Modifier.isAbstract(md.modifiers) && !Modifier.isStatic(md.modifiers)) {
if (md.getAnnotations(MY_TYPE)) continue
if (controllerMethodAnn && md.getAnnotations(controllerMethodAnn)) continue
weaveTransactionalMethod(source, classNode, annotationNode, md);
}
}
}
ClassNode getAnnotationClassNode(String annotationName) {
try {
final classLoader = Thread.currentThread().contextClassLoader
final clazz = classLoader.loadClass(annotationName)
return new ClassNode(clazz)
} catch (e) {
return null
}
}
protected void weaveTransactionalMethod(SourceUnit source, ClassNode classNode, AnnotationNode annotationNode, MethodNode methodNode) {
if(isApplied(methodNode, this.getClass())) {
return
}
markApplied(methodNode, this.getClass())
MethodCallExpression originalMethodCall = moveOriginalCodeToNewMethod(source, classNode, methodNode)
BlockStatement methodBody = new BlockStatement()
final transactionAttributeClassNode = ClassHelper.make(RuleBasedTransactionAttribute)
final transactionAttributeVar = new VariableExpression('$transactionAttribute', transactionAttributeClassNode)
methodBody.addStatement(
new ExpressionStatement(
new DeclarationExpression(
transactionAttributeVar,
GrailsASTUtils.ASSIGNMENT_OPERATOR,
new ConstructorCallExpression(transactionAttributeClassNode, GrailsASTUtils.ZERO_ARGUMENTS)
)
)
)
// remove possible @CS & @TC SKIP annotation from original method node
removeCompileStaticAnnotations(methodNode)
// add @CS annotation to original method node
addCompileStaticAnnotation(methodNode)
applyTransactionalAttributeSettings(annotationNode, transactionAttributeVar, methodBody)
final executeMethodParameterTypes = [new Parameter(ClassHelper.make(TransactionStatus), "transactionStatus")] as Parameter[]
final callCallExpression = new ClosureExpression(executeMethodParameterTypes, new ExpressionStatement(originalMethodCall))
final constructorArgs = new ArgumentListExpression()
constructorArgs.addExpression(new PropertyExpression(buildThisExpression(), PROPERTY_TRANSACTION_MANAGER))
constructorArgs.addExpression(transactionAttributeVar)
final transactionTemplateClassNode = ClassHelper.make(GrailsTransactionTemplate)
final transactionTemplateVar = new VariableExpression('$transactionTemplate', transactionTemplateClassNode)
methodBody.addStatement(
new ExpressionStatement(
new DeclarationExpression(
transactionTemplateVar,
GrailsASTUtils.ASSIGNMENT_OPERATOR,
new ConstructorCallExpression(transactionTemplateClassNode, constructorArgs)
)
)
)
final methodArgs = new ArgumentListExpression()
methodArgs.addExpression(callCallExpression)
final executeMethodCallExpression = new MethodCallExpression(transactionTemplateVar, METHOD_EXECUTE, methodArgs)
final executeMethodNode = transactionTemplateClassNode.getMethod("execute", executeMethodParameterTypes)
executeMethodCallExpression.setMethodTarget(executeMethodNode)
if(methodNode.getReturnType() != ClassHelper.VOID_TYPE) {
methodBody.addStatement(new ReturnStatement(new CastExpression(methodNode.getReturnType(), executeMethodCallExpression)))
} else {
methodBody.addStatement(new ExpressionStatement(executeMethodCallExpression));
}
methodNode.setCode(methodBody)
processVariableScopes(source, classNode, methodNode)
}
protected applyTransactionalAttributeSettings(AnnotationNode annotationNode, VariableExpression transactionAttributeVar, BlockStatement methodBody) {
final rollbackRuleAttributeClassNode = ClassHelper.make(RollbackRuleAttribute)
final noRollbackRuleAttributeClassNode = ClassHelper.make(NoRollbackRuleAttribute)
final members = annotationNode.getMembers()
int rollbackRuleId = 0
members.each { String name, Expression expr ->
if (name == 'rollbackFor' || name == 'rollbackForClassName' || name == 'noRollbackFor' || name == 'noRollbackForClassName') {
final targetClassNode = (name == 'rollbackFor' || name == 'rollbackForClassName') ? rollbackRuleAttributeClassNode : noRollbackRuleAttributeClassNode
name = 'rollbackRules'
if (expr instanceof ListExpression) {
for(exprItem in ((ListExpression)expr).expressions) {
appendRuleElement(methodBody, transactionAttributeVar, name, new ConstructorCallExpression(targetClassNode, exprItem))
}
} else {
appendRuleElement(methodBody, transactionAttributeVar, name, new ConstructorCallExpression(targetClassNode, expr))
}
} else {
if (name == 'isolation') {
name = 'isolationLevel'
expr = new MethodCallExpression(expr, "value", new ArgumentListExpression())
} else if (name == 'propagation') {
name = 'propagationBehavior'
expr = new MethodCallExpression(expr, "value", new ArgumentListExpression())
}
methodBody.addStatement(
new ExpressionStatement(
new BinaryExpression(new PropertyExpression(transactionAttributeVar, name),
Token.newSymbol(Types.EQUAL, 0, 0),
expr)
)
)
}
}
}
private appendRuleElement(BlockStatement methodBody, VariableExpression transactionAttributeVar, String name, Expression expr) {
final rollbackRuleAttributeClassNode = ClassHelper.make(RollbackRuleAttribute)
ClassNode rollbackRulesListClassNode = nonGeneric(ClassHelper.make(List), rollbackRuleAttributeClassNode)
methodBody.addStatement(
new ExpressionStatement(
new MethodCallExpression(
new CastExpression(rollbackRulesListClassNode, buildGetPropertyExpression(transactionAttributeVar, name, transactionAttributeVar.getType())),
'add',
expr
)
)
)
}
protected MethodCallExpression moveOriginalCodeToNewMethod(SourceUnit source, ClassNode classNode, MethodNode methodNode) {
String renamedMethodName = '$tt__' + methodNode.getName()
final transactionStatusParameter = new Parameter(ClassHelper.make(TransactionStatus), "transactionStatus")
def newParameters = methodNode.getParameters() ? (copyParameters(((methodNode.getParameters() as List) + [transactionStatusParameter]) as Parameter[])) : [transactionStatusParameter] as Parameter[]
MethodNode renamedMethodNode = new MethodNode(
renamedMethodName,
Modifier.PROTECTED, methodNode.getReturnType().getPlainNodeReference(),
newParameters,
GrailsArtefactClassInjector.EMPTY_CLASS_ARRAY,
methodNode.code
);
methodNode.setCode(null)
copyAnnotations(methodNode, renamedMethodNode, null, ["grails.transaction.Transactional"] as Set)
classNode.addMethod(renamedMethodNode)
processVariableScopes(source, classNode, renamedMethodNode)
final originalMethodCall = new MethodCallExpression(new VariableExpression("this"), renamedMethodName, new ArgumentListExpression(renamedMethodNode.parameters))
originalMethodCall.setImplicitThis(false)
originalMethodCall.setMethodTarget(renamedMethodNode)
originalMethodCall
}
protected void weaveTransactionManagerAware(SourceUnit source, ClassNode declaringClassNode) {
ClassNode transactionManagerAwareInterface = ClassHelper.make(TransactionManagerAware)
if (!GrailsASTUtils.findInterface(declaringClassNode, transactionManagerAwareInterface)) {
declaringClassNode.addInterface(transactionManagerAwareInterface)
//add the transactionManager property
final transactionManagerProperty = declaringClassNode.getProperty(PROPERTY_TRANSACTION_MANAGER)
if (!transactionManagerProperty) {
declaringClassNode.addProperty(PROPERTY_TRANSACTION_MANAGER, Modifier.PUBLIC, ClassHelper.make(PlatformTransactionManager), null, null, null);
}
}
}
}