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.migration.bundle.ForeignKeyBundle 20 21 /** 22 * Keeps information about a foreign key. 23 */ 24 data class ForeignKey(val parentTable: String, 25 val parentColumns: List<String>, 26 val childFields: List<Field>, 27 val onDelete: ForeignKeyAction, 28 val onUpdate: ForeignKeyAction, 29 val deferred: Boolean) : HasSchemaIdentity { getIdKeynull30 override fun getIdKey(): String { 31 return parentTable + 32 "-${parentColumns.joinToString(",")}" + 33 "-${childFields.joinToString(",") {it.columnName}}" + 34 "-${onDelete.sqlName}" + 35 "-${onUpdate.sqlName}" + 36 "-$deferred" 37 } 38 databaseDefinitionnull39 fun databaseDefinition(): String { 40 return "FOREIGN KEY(${joinEscaped(childFields.map { it.columnName })})" + 41 " REFERENCES `$parentTable`(${joinEscaped(parentColumns)})" + 42 " ON UPDATE ${onUpdate.sqlName}" + 43 " ON DELETE ${onDelete.sqlName}" + 44 " ${deferredDeclaration()}" 45 } 46 deferredDeclarationnull47 private fun deferredDeclaration(): String { 48 return if (deferred) { 49 "DEFERRABLE INITIALLY DEFERRED" 50 } else { 51 "" 52 } 53 } 54 joinEscapednull55 private fun joinEscaped(values: Iterable<String>) = values.joinToString(", ") { "`$it`" } 56 toBundlenull57 fun toBundle(): ForeignKeyBundle = ForeignKeyBundle( 58 parentTable, onDelete.sqlName, onUpdate.sqlName, 59 childFields.map { it.columnName }, 60 parentColumns 61 ) 62 } 63