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.vo 18 19 import androidx.room.compiler.processing.XType 20 21 /** Value object created from processing a @Relation annotation. */ 22 class Relation( 23 val entity: EntityOrView, 24 // return type. e..g. String in @Relation List<String> 25 val dataClassType: XType, 26 // property in data class that holds these relations (e.g. List<Pet> pets) 27 val property: Property, 28 // the parent property referenced for matching 29 val parentProperty: Property, 30 // the property referenced for querying. does not need to be in the response but the query 31 // we generate always has it in the response. 32 val entityProperty: Property, 33 // Used for joining on a many-to-many relation 34 val junction: Junction?, 35 // the projection for the query 36 val projection: List<String> 37 ) { <lambda>null38 val dataClassTypeName by lazy { dataClassType.asTypeName() } 39 createLoadAllSqlnull40 fun createLoadAllSql(): String { 41 val resultProperties = projection.toSet() 42 return createSelect(resultProperties) 43 } 44 <lambda>null45 private fun createSelect(resultProperties: Set<String>) = buildString { 46 if (junction != null) { 47 val resultColumns = 48 resultProperties.map { "`${entity.tableName}`.`$it` AS `$it`" } + 49 "_junction.`${junction.parentProperty.columnName}`" 50 append("SELECT ${resultColumns.joinToString(",")}") 51 append(" FROM `${junction.entity.tableName}` AS _junction") 52 append( 53 " INNER JOIN `${entity.tableName}` ON" + 54 " (_junction.`${junction.entityProperty.columnName}`" + 55 " = `${entity.tableName}`.`${entityProperty.columnName}`)" 56 ) 57 append(" WHERE _junction.`${junction.parentProperty.columnName}` IN (:args)") 58 } else { 59 val resultColumns = 60 resultProperties.map { "`$it`" }.toSet() + "`${entityProperty.columnName}`" 61 append("SELECT ${resultColumns.joinToString(",")}") 62 append(" FROM `${entity.tableName}`") 63 append(" WHERE `${entityProperty.columnName}` IN (:args)") 64 } 65 } 66 } 67