1 /* 2 * 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.server.healthconnect.storage.datatypehelpers; 18 19 import com.android.server.healthconnect.storage.TransactionManager; 20 import com.android.server.healthconnect.storage.request.DeleteTableRequest; 21 22 import java.util.HashSet; 23 import java.util.Set; 24 25 /** 26 * Parent class for the database helper classes containing common methods 27 * 28 * @hide 29 */ 30 public abstract class DatabaseHelper { 31 DatabaseHelper(DatabaseHelpers databaseHelpers)32 protected DatabaseHelper(DatabaseHelpers databaseHelpers) { 33 databaseHelpers.add(this); 34 } 35 36 /** Deletes all entries from the database and clears the cache for the helper class. */ clearData(TransactionManager transactionManager)37 public synchronized void clearData(TransactionManager transactionManager) { 38 transactionManager.delete(new DeleteTableRequest(getMainTableName())); 39 clearCache(); 40 } 41 clearCache()42 protected void clearCache() {} 43 getMainTableName()44 protected abstract String getMainTableName(); 45 46 /** A collection of {@link DatabaseHelper}. */ 47 public static final class DatabaseHelpers { 48 49 private final Set<DatabaseHelper> mDatabaseHelpers = new HashSet<>(); 50 51 /** 52 * Deletes all entries from the database and clears the cache for all the helper class. 53 * 54 * <p>This function is only used for testing, do not use in production. 55 */ clearAllData(TransactionManager transactionManager)56 public void clearAllData(TransactionManager transactionManager) { 57 for (DatabaseHelper databaseHelper : mDatabaseHelpers) { 58 databaseHelper.clearData(transactionManager); 59 } 60 } 61 62 /** Clears cache in all the helpers. */ clearAllCache()63 public void clearAllCache() { 64 for (DatabaseHelper databaseHelper : mDatabaseHelpers) { 65 databaseHelper.clearCache(); 66 } 67 } 68 add(DatabaseHelper databaseHelper)69 private void add(DatabaseHelper databaseHelper) { 70 mDatabaseHelpers.add(databaseHelper); 71 } 72 } 73 } 74