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 package androidx.room.solver.query.result
17 
18 import androidx.room.ext.AndroidTypeNames
19 import androidx.room.ext.L
20 import androidx.room.ext.N
21 import androidx.room.ext.T
22 import androidx.room.solver.CodeGenScope
23 import androidx.room.writer.DaoWriter
24 import com.squareup.javapoet.FieldSpec
25 
26 /**
27  * Instantly runs and returns the query.
28  */
29 class InstantQueryResultBinder(adapter: QueryResultAdapter?) : QueryResultBinder(adapter) {
convertAndReturnnull30     override fun convertAndReturn(roomSQLiteQueryVar: String,
31                                   canReleaseQuery: Boolean,
32                                   dbField: FieldSpec,
33                                   inTransaction: Boolean,
34                                   scope: CodeGenScope) {
35         val transactionWrapper = if (inTransaction) {
36             scope.builder().transactionWrapper(dbField)
37         } else {
38             null
39         }
40         transactionWrapper?.beginTransactionWithControlFlow()
41         scope.builder().apply {
42             val outVar = scope.getTmpVar("_result")
43             val cursorVar = scope.getTmpVar("_cursor")
44             addStatement("final $T $L = $N.query($L)", AndroidTypeNames.CURSOR, cursorVar,
45                     DaoWriter.dbField, roomSQLiteQueryVar)
46             beginControlFlow("try").apply {
47                 adapter?.convert(outVar, cursorVar, scope)
48                 transactionWrapper?.commitTransaction()
49                 addStatement("return $L", outVar)
50             }
51             nextControlFlow("finally").apply {
52                 addStatement("$L.close()", cursorVar)
53                 if (canReleaseQuery) {
54                     addStatement("$L.release()", roomSQLiteQueryVar)
55                 }
56             }
57             endControlFlow()
58         }
59         transactionWrapper?.endTransactionWithControlFlow()
60     }
61 }
62