1 /*
<lambda>null2  * Copyright (C) 2023 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 com.android.systemui.communal.data.db
18 
19 import android.content.Context
20 import androidx.annotation.VisibleForTesting
21 import androidx.room.Database
22 import androidx.room.Room
23 import androidx.room.RoomDatabase
24 import com.android.systemui.res.R
25 
26 @Database(entities = [CommunalWidgetItem::class, CommunalItemRank::class], version = 1)
27 abstract class CommunalDatabase : RoomDatabase() {
28     abstract fun communalWidgetDao(): CommunalWidgetDao
29 
30     companion object {
31         private var instance: CommunalDatabase? = null
32 
33         /**
34          * Gets a singleton instance of the communal database. If this is called for the first time
35          * globally, a new instance is created.
36          *
37          * @param context The context the database is created in. Only effective when a new instance
38          *   is created.
39          * @param callback An optional callback registered to the database. Only effective when a
40          *   new instance is created.
41          */
42         fun getInstance(
43             context: Context,
44             callback: Callback? = null,
45         ): CommunalDatabase {
46             if (instance == null) {
47                 instance =
48                     Room.databaseBuilder(
49                             context,
50                             CommunalDatabase::class.java,
51                             context.resources.getString(R.string.config_communalDatabase)
52                         )
53                         .also { builder ->
54                             builder.fallbackToDestructiveMigration(dropAllTables = false)
55                             callback?.let { callback -> builder.addCallback(callback) }
56                         }
57                         .build()
58             }
59 
60             return instance!!
61         }
62 
63         @VisibleForTesting
64         fun setInstance(database: CommunalDatabase) {
65             instance = database
66         }
67     }
68 }
69