1 /* 2 * Copyright 2024 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.migration.bundle 18 19 import androidx.annotation.RestrictTo 20 import kotlinx.serialization.SerialName 21 import kotlinx.serialization.Serializable 22 23 /** Base class that holds common schema information about an entity. */ 24 @Serializable 25 @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) 26 sealed class BaseEntityBundle { 27 @SerialName("tableName") abstract val tableName: String 28 @SerialName("createSql") abstract val createSql: String 29 @SerialName("fields") abstract val fields: List<FieldBundle> 30 @SerialName("primaryKey") abstract val primaryKey: PrimaryKeyBundle 31 @SerialName("indices") abstract val indices: List<IndexBundle> 32 @SerialName("foreignKeys") abstract val foreignKeys: List<ForeignKeyBundle> 33 34 companion object { 35 const val NEW_TABLE_PREFIX: String = "_new_" 36 } 37 38 val newTableName: String 39 get() { 40 return NEW_TABLE_PREFIX + tableName 41 } 42 <lambda>null43 val fieldsByColumnName: Map<String, FieldBundle> by lazy { 44 fields.associateBy { it.columnName } 45 } 46 47 /** CREATE TABLE SQL query that uses the actual table name. */ createTablenull48 fun createTable(): String { 49 return replaceTableName(createSql, tableName) 50 } 51 52 /** CREATE TABLE SQL query that uses the table name with "new" prefix. */ createNewTablenull53 fun createNewTable(): String { 54 return replaceTableName(createSql, newTableName) 55 } 56 57 /** Renames the table with [newTableName] to [tableName]. */ renameToOriginalnull58 fun renameToOriginal(): String { 59 return "ALTER TABLE $newTableName RENAME TO $tableName" 60 } 61 62 /** Creates the list of SQL queries that are necessary to create this entity. */ buildCreateQueriesnull63 abstract fun buildCreateQueries(): List<String> 64 } 65