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 17 package androidx.room.solver.query.result 18 19 import androidx.room.ext.AndroidTypeNames 20 import androidx.room.ext.L 21 import androidx.room.ext.N 22 import androidx.room.ext.T 23 import androidx.room.solver.CodeGenScope 24 import androidx.room.writer.DaoWriter 25 import com.squareup.javapoet.FieldSpec 26 import com.squareup.javapoet.MethodSpec 27 import javax.lang.model.element.Modifier 28 29 /** 30 * Base class for query result binders that observe the database. It includes common functionality 31 * like creating a finalizer to release the query or creating the actual adapter call code. 32 */ 33 abstract class BaseObservableQueryResultBinder(adapter: QueryResultAdapter?) 34 : QueryResultBinder(adapter) { 35 createFinalizeMethodnull36 protected fun createFinalizeMethod(roomSQLiteQueryVar: String): MethodSpec { 37 return MethodSpec.methodBuilder("finalize").apply { 38 addModifiers(Modifier.PROTECTED) 39 addAnnotation(Override::class.java) 40 addStatement("$L.release()", roomSQLiteQueryVar) 41 }.build() 42 } 43 createRunQueryAndReturnStatementsnull44 protected fun createRunQueryAndReturnStatements(builder: MethodSpec.Builder, 45 roomSQLiteQueryVar: String, 46 dbField: FieldSpec, 47 inTransaction: Boolean, 48 scope: CodeGenScope) { 49 val transactionWrapper = if (inTransaction) { 50 builder.transactionWrapper(dbField) 51 } else { 52 null 53 } 54 val outVar = scope.getTmpVar("_result") 55 val cursorVar = scope.getTmpVar("_cursor") 56 transactionWrapper?.beginTransactionWithControlFlow() 57 builder.apply { 58 addStatement("final $T $L = $N.query($L)", AndroidTypeNames.CURSOR, cursorVar, 59 DaoWriter.dbField, roomSQLiteQueryVar) 60 beginControlFlow("try").apply { 61 val adapterScope = scope.fork() 62 adapter?.convert(outVar, cursorVar, adapterScope) 63 addCode(adapterScope.builder().build()) 64 transactionWrapper?.commitTransaction() 65 addStatement("return $L", outVar) 66 } 67 nextControlFlow("finally").apply { 68 addStatement("$L.close()", cursorVar) 69 } 70 endControlFlow() 71 } 72 transactionWrapper?.endTransactionWithControlFlow() 73 } 74 } 75