1 /* 2 * Copyright (C) 2022 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.adservices.service.common.cache; 18 19 import static com.android.adservices.service.common.cache.CacheDatabase.DATABASE_VERSION; 20 21 import android.content.Context; 22 23 import androidx.annotation.NonNull; 24 import androidx.room.AutoMigration; 25 import androidx.room.Database; 26 import androidx.room.RoomDatabase; 27 import androidx.room.TypeConverters; 28 29 import com.android.adservices.data.common.FledgeRoomConverters; 30 import com.android.adservices.service.common.compat.FileCompatUtils; 31 import com.android.internal.annotations.GuardedBy; 32 33 import java.util.Objects; 34 35 /** A class that represents the database for caching web requests related to Fledge */ 36 @Database( 37 entities = {DBCacheEntry.class}, 38 autoMigrations = { 39 @AutoMigration(from = 1, to = 2), 40 }, 41 version = DATABASE_VERSION) 42 @TypeConverters({FledgeRoomConverters.class}) 43 public abstract class CacheDatabase extends RoomDatabase { 44 private static final Object SINGLETON_LOCK = new Object(); 45 46 // TODO(b/270615351): Create migration rollback test for version bump 47 public static final int DATABASE_VERSION = 2; 48 public static final String DATABASE_NAME = 49 FileCompatUtils.getAdservicesFilename("fledgehttpcache.db"); 50 51 @GuardedBy("SINGLETON_LOCK") 52 private static CacheDatabase sSingleton = null; 53 54 /** Returns an instance of the CacheDatabase given a context. */ getInstance(@onNull Context context)55 public static CacheDatabase getInstance(@NonNull Context context) { 56 Objects.requireNonNull(context); 57 synchronized (SINGLETON_LOCK) { 58 if (Objects.isNull(sSingleton)) { 59 sSingleton = 60 FileCompatUtils.roomDatabaseBuilderHelper( 61 context, CacheDatabase.class, DATABASE_NAME) 62 .fallbackToDestructiveMigration() 63 .build(); 64 } 65 return sSingleton; 66 } 67 } 68 69 /** @return a Dao to access cached entries */ getCacheEntryDao()70 public abstract CacheEntryDao getCacheEntryDao(); 71 } 72