NewPipe/app/src/main/java/org/schabi/newpipe/NewPipeDatabase.java

66 lines
2 KiB
Java
Raw Normal View History

package org.schabi.newpipe;
import android.content.Context;
2020-02-21 13:13:01 +00:00
import android.database.Cursor;
2019-10-04 12:59:08 +00:00
import androidx.annotation.NonNull;
2020-02-21 13:13:01 +00:00
import androidx.room.Room;
import org.schabi.newpipe.database.AppDatabase;
import static org.schabi.newpipe.database.AppDatabase.DATABASE_NAME;
import static org.schabi.newpipe.database.Migrations.MIGRATION_1_2;
import static org.schabi.newpipe.database.Migrations.MIGRATION_2_3;
public final class NewPipeDatabase {
private static volatile AppDatabase databaseInstance;
private NewPipeDatabase() {
//no instance
}
private static AppDatabase getDatabase(final Context context) {
return Room
.databaseBuilder(context.getApplicationContext(), AppDatabase.class, DATABASE_NAME)
.addMigrations(MIGRATION_1_2, MIGRATION_2_3)
.build();
}
@NonNull
public static AppDatabase getInstance(@NonNull final Context context) {
AppDatabase result = databaseInstance;
if (result == null) {
synchronized (NewPipeDatabase.class) {
result = databaseInstance;
if (result == null) {
databaseInstance = getDatabase(context);
result = databaseInstance;
}
}
}
return result;
}
2020-02-21 13:13:01 +00:00
public static void checkpoint() {
if (databaseInstance == null) {
2020-02-21 13:13:01 +00:00
throw new IllegalStateException("database is not initialized");
}
2020-08-16 08:24:58 +00:00
final Cursor c = databaseInstance.query("pragma wal_checkpoint(full)", null);
if (c.moveToFirst() && c.getInt(0) == 1) {
2020-02-21 13:13:01 +00:00
throw new RuntimeException("Checkpoint was blocked from completing");
}
}
2021-07-10 12:46:51 +00:00
public static void close() {
if (databaseInstance != null) {
synchronized (NewPipeDatabase.class) {
if (databaseInstance != null) {
databaseInstance.close();
databaseInstance = null;
}
}
}
}
}