1 /* <lambda>null2 * Copyright (C) 2016 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.compiler.codegen.CodeLanguage 20 import androidx.room.compiler.codegen.XCodeBlock.Builder.Companion.applyTo 21 import androidx.room.compiler.processing.XNullability 22 import androidx.room.solver.CodeGenScope 23 24 /** Wraps a row adapter when there is only 1 item in the result */ 25 class SingleItemQueryResultAdapter(private val rowAdapter: RowAdapter) : 26 QueryResultAdapter(listOf(rowAdapter)) { 27 val type = rowAdapter.out 28 29 override fun convert(outVarName: String, stmtVarName: String, scope: CodeGenScope) { 30 scope.builder.apply { 31 rowAdapter.onStatementReady(stmtVarName = stmtVarName, scope = scope) 32 addLocalVariable(outVarName, type.asTypeName()) 33 beginControlFlow("if (%L.step())", stmtVarName).apply { 34 rowAdapter.convert(outVarName, stmtVarName, scope) 35 } 36 nextControlFlow("else").applyTo { language -> 37 val defaultValue = rowAdapter.out.defaultValue() 38 if ( 39 language == CodeLanguage.KOTLIN && 40 type.nullability == XNullability.NONNULL && 41 defaultValue == "null" 42 ) { 43 addStatement( 44 "error(%S)", 45 "The query result was empty, but expected a single row to " + 46 "return a NON-NULL object of " + 47 "type <${type.asTypeName().toString(language)}>." 48 ) 49 } else { 50 addStatement("%L = %L", outVarName, rowAdapter.out.defaultValue()) 51 } 52 } 53 endControlFlow() 54 } 55 } 56 } 57