1/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package androidx.room.solver.query.result
18
19import androidx.room.ext.N
20import com.squareup.javapoet.CodeBlock
21import com.squareup.javapoet.FieldSpec
22import com.squareup.javapoet.MethodSpec
23
24/**
25 * helper class to create correct transaction code.
26 */
27interface TransactionWrapper {
28    fun beginTransactionWithControlFlow()
29    fun commitTransaction()
30    fun endTransactionWithControlFlow()
31}
32
33fun MethodSpec.Builder.transactionWrapper(dbField: FieldSpec) = object : TransactionWrapper {
34    override fun beginTransactionWithControlFlow() {
35        addStatement("$N.beginTransaction()", dbField)
36        beginControlFlow("try")
37    }
38
39    override fun commitTransaction() {
40        addStatement("$N.setTransactionSuccessful()", dbField)
41    }
42
43    override fun endTransactionWithControlFlow() {
44        nextControlFlow("finally")
45        addStatement("$N.endTransaction()", dbField)
46        endControlFlow()
47    }
48}
49
50fun CodeBlock.Builder.transactionWrapper(dbField: FieldSpec) = object : TransactionWrapper {
51    override fun beginTransactionWithControlFlow() {
52        addStatement("$N.beginTransaction()", dbField)
53        beginControlFlow("try")
54    }
55
56    override fun commitTransaction() {
57        addStatement("$N.setTransactionSuccessful()", dbField)
58    }
59
60    override fun endTransactionWithControlFlow() {
61        nextControlFlow("finally")
62        addStatement("$N.endTransaction()", dbField)
63        endControlFlow()
64    }
65}
66