2 * Copyright © 2021 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe is free software: you can distribute it and/or modify it
5 * under the term of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your opinion), any later version.
9 * MoLe is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License terms for details.
14 * You should have received a copy of the GNU General Public License
15 * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.db;
20 import android.content.res.Resources;
21 import android.database.Cursor;
22 import android.database.SQLException;
24 import androidx.annotation.NonNull;
25 import androidx.lifecycle.MutableLiveData;
26 import androidx.room.Database;
27 import androidx.room.Room;
28 import androidx.room.RoomDatabase;
29 import androidx.room.migration.Migration;
30 import androidx.sqlite.db.SupportSQLiteDatabase;
32 import net.ktnx.mobileledger.App;
33 import net.ktnx.mobileledger.dao.AccountDAO;
34 import net.ktnx.mobileledger.dao.AccountValueDAO;
35 import net.ktnx.mobileledger.dao.CurrencyDAO;
36 import net.ktnx.mobileledger.dao.OptionDAO;
37 import net.ktnx.mobileledger.dao.ProfileDAO;
38 import net.ktnx.mobileledger.dao.TemplateAccountDAO;
39 import net.ktnx.mobileledger.dao.TemplateHeaderDAO;
40 import net.ktnx.mobileledger.dao.TransactionAccountDAO;
41 import net.ktnx.mobileledger.dao.TransactionDAO;
42 import net.ktnx.mobileledger.utils.Logger;
44 import java.io.BufferedReader;
45 import java.io.IOException;
46 import java.io.InputStream;
47 import java.io.InputStreamReader;
48 import java.util.Locale;
49 import java.util.UUID;
50 import java.util.regex.Matcher;
51 import java.util.regex.Pattern;
53 import static net.ktnx.mobileledger.utils.Logger.debug;
55 @Database(version = DB.REVISION,
56 entities = {TemplateHeader.class, TemplateAccount.class, Currency.class, Account.class,
57 Profile.class, Option.class, AccountValue.class, Transaction.class,
58 TransactionAccount.class
60 abstract public class DB extends RoomDatabase {
61 public static final int REVISION = 64;
62 public static final String DB_NAME = "MoLe.db";
63 public static final MutableLiveData<Boolean> initComplete = new MutableLiveData<>(false);
64 private static DB instance;
65 public static DB get() {
68 synchronized (DB.class) {
72 RoomDatabase.Builder<DB> builder =
73 Room.databaseBuilder(App.instance, DB.class, DB_NAME);
74 builder.addMigrations(
75 new Migration[]{singleVersionMigration(17), singleVersionMigration(18),
76 singleVersionMigration(19), singleVersionMigration(20),
77 multiVersionMigration(20, 22), multiVersionMigration(22, 30),
78 multiVersionMigration(30, 32), multiVersionMigration(32, 34),
79 multiVersionMigration(34, 40), singleVersionMigration(41),
80 multiVersionMigration(41, 58), singleVersionMigration(59),
81 singleVersionMigration(60), singleVersionMigration(61),
82 singleVersionMigration(62), singleVersionMigration(63),
83 singleVersionMigration(64)
85 .addCallback(new Callback() {
87 public void onOpen(@NonNull SupportSQLiteDatabase db) {
89 db.execSQL("PRAGMA foreign_keys = ON");
90 db.execSQL("pragma case_sensitive_like" + "=ON;");
95 // if (BuildConfig.DEBUG)
96 // builder.setQueryCallback(((sqlQuery, bindArgs) -> Logger.debug("room", sqlQuery)),
97 // Executors.newSingleThreadExecutor());
99 return instance = builder.build();
102 private static Migration singleVersionMigration(int toVersion) {
103 return new Migration(toVersion - 1, toVersion) {
105 public void migrate(@NonNull SupportSQLiteDatabase db) {
106 String fileName = String.format(Locale.US, "db_%d", toVersion);
108 applyRevisionFile(db, fileName);
110 // when migrating to version 59, migrate profile/theme options to the
112 if (toVersion == 59) {
113 try (Cursor c = db.query(
114 "SELECT p.id, p.theme FROM profiles p WHERE p.id=(SELECT o.value " +
115 "FROM options o WHERE o.profile_id=0 AND o.name=?)",
116 new Object[]{"profile_id"}))
118 if (c.moveToFirst()) {
119 long currentProfileId = c.getLong(0);
120 int currentTheme = c.getInt(1);
122 if (currentProfileId >= 0 && currentTheme >= 0) {
123 App.storeStartupProfileAndTheme(currentProfileId, currentTheme);
128 if (toVersion == 63) {
129 try (Cursor c = db.query("SELECT id FROM templates")) {
130 while (c.moveToNext()) {
131 db.execSQL("UPDATE templates SET uuid=? WHERE id=?",
132 new Object[]{UUID.randomUUID().toString(), c.getLong(0)});
139 private static Migration dummyVersionMigration(int toVersion) {
140 return new Migration(toVersion - 1, toVersion) {
142 public void migrate(@NonNull SupportSQLiteDatabase db) {
144 String.format(Locale.ROOT, "Dummy DB migration to version %d", toVersion));
148 private static Migration multiVersionMigration(int fromVersion, int toVersion) {
149 return new Migration(fromVersion, toVersion) {
151 public void migrate(@NonNull SupportSQLiteDatabase db) {
152 String fileName = String.format(Locale.US, "db_%d_%d", fromVersion, toVersion);
154 applyRevisionFile(db, fileName);
158 public static void applyRevisionFile(@NonNull SupportSQLiteDatabase db, String fileName) {
159 final Resources rm = App.instance.getResources();
160 int res_id = rm.getIdentifier(fileName, "raw", App.instance.getPackageName());
162 throw new SQLException(String.format(Locale.US, "No resource for %s", fileName));
164 try (InputStream res = rm.openRawResource(res_id)) {
165 debug("db", "Applying " + fileName);
166 InputStreamReader isr = new InputStreamReader(res);
167 BufferedReader reader = new BufferedReader(isr);
169 Pattern endOfStatement = Pattern.compile(";\\s*(?:--.*)?$");
172 String sqlStatement = null;
174 while ((line = reader.readLine()) != null) {
176 if (line.startsWith("--"))
181 if (sqlStatement == null)
184 sqlStatement = sqlStatement.concat(" " + line);
186 Matcher m = endOfStatement.matcher(line);
191 db.execSQL(sqlStatement);
194 catch (Exception e) {
195 throw new RuntimeException(
196 String.format("Error applying %s, line %d, statement: %s", fileName,
197 lineNo, sqlStatement), e);
201 if (sqlStatement != null)
202 throw new RuntimeException(String.format(
203 "Error applying %s: EOF after continuation. Line %s, Incomplete " +
204 "statement: %s", fileName, lineNo, sqlStatement));
207 catch (IOException e) {
208 throw new RuntimeException(String.format("Error opening raw resource for %s", fileName),
212 public abstract TemplateHeaderDAO getTemplateDAO();
214 public abstract TemplateAccountDAO getTemplateAccountDAO();
216 public abstract CurrencyDAO getCurrencyDAO();
218 public abstract AccountDAO getAccountDAO();
220 public abstract AccountValueDAO getAccountValueDAO();
222 public abstract TransactionDAO getTransactionDAO();
224 public abstract TransactionAccountDAO getTransactionAccountDAO();
226 public abstract OptionDAO getOptionDAO();
228 public abstract ProfileDAO getProfileDAO();