1 /* 2 * Copyright 2018 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.writer 18 19 import androidx.room.compiler.codegen.XCodeBlock 20 import androidx.room.compiler.codegen.XTypeName 21 import androidx.room.solver.CodeGenScope 22 23 /** Common interface for database validation witters. */ 24 abstract class ValidationWriter { 25 26 private lateinit var countingScope: CountingCodeGenScope 27 writenull28 fun write(dbParamName: String, scope: CodeGenScope) { 29 countingScope = CountingCodeGenScope(scope) 30 write(dbParamName, countingScope) 31 } 32 writenull33 protected abstract fun write(connectionParamName: String, scope: CountingCodeGenScope) 34 35 /** The estimated amount of statements this writer will write. */ 36 fun statementCount() = countingScope.statementCount() 37 38 protected class CountingCodeGenScope(private val scope: CodeGenScope) { 39 40 val builder = CodeBlockWrapper(scope.builder) 41 42 fun getTmpVar(prefix: String) = scope.getTmpVar(prefix) 43 44 fun statementCount() = builder.statementCount 45 } 46 47 // A wrapper class that counts statements added to a CodeBlock 48 protected class CodeBlockWrapper(private val builder: XCodeBlock.Builder) : <lambda>null49 XCodeBlock.Builder by builder { 50 51 var statementCount = 0 52 private set 53 54 override fun add(format: String, vararg args: Any?): XCodeBlock.Builder { 55 statementCount++ 56 builder.add(format, *args) 57 return this 58 } 59 60 override fun addLocalVariable( 61 name: String, 62 typeName: XTypeName, 63 isMutable: Boolean, 64 assignExpr: XCodeBlock? 65 ): XCodeBlock.Builder { 66 statementCount++ 67 builder.addLocalVariable(name, typeName, isMutable, assignExpr) 68 return this 69 } 70 71 override fun addStatement(format: String, vararg args: Any?): CodeBlockWrapper { 72 statementCount++ 73 builder.addStatement(format, *args) 74 return this 75 } 76 77 override fun beginControlFlow(controlFlow: String, vararg args: Any?): CodeBlockWrapper { 78 statementCount++ 79 builder.beginControlFlow(controlFlow, *args) 80 return this 81 } 82 83 override fun endControlFlow(): CodeBlockWrapper { 84 builder.endControlFlow() 85 return this 86 } 87 } 88 } 89