• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 com.android.photopicker.core.database
18 
19 import android.content.Context
20 import com.android.photopicker.PhotopickerApplication
21 import com.android.photopicker.core.banners.BannerStateDao
22 
23 /**
24  * This is a prod implementation that relies on an actual backing database.
25  *
26  * @param appContext The application context required to connect to the database.
27  */
28 class DatabaseManagerImpl(appContext: Context) : DatabaseManager {
29 
30     /**
31      * A running database connection to the [PhotopickerDatabase]. This is a wrapper that the room
32      * library puts around the database to manage connection pooling, and read/write access
33      */
34     private val database: PhotopickerDatabase
35 
36     init {
37         // The [PhotopickerDatabase] instance is created during Application#onCreate
38         // so a reference of it can be fetched from the application.
39         val application = appContext as? PhotopickerApplication
<lambda>null40         checkNotNull(application) {
41             "PhotopickerApplication context was not provided to DatabaseManager"
42         }
43         database = application.database
44     }
45 
46     @Suppress("UNCHECKED_CAST")
acquireDaonull47     override fun <T> acquireDao(daoClass: Class<T>): T {
48         with(daoClass) {
49             return when {
50                 isAssignableFrom(BannerStateDao::class.java) -> database.bannerStateDao() as T
51                 else ->
52                     throw IllegalArgumentException(
53                         "Cannot acquire ${daoClass.simpleName} from DatabaseManagerImpl"
54                     )
55             }
56         }
57     }
58 }
59