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