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 org.jetbrains.annotations.NotNull;
46 import java.io.BufferedReader;
47 import java.io.IOException;
48 import java.io.InputStream;
49 import java.io.InputStreamReader;
50 import java.util.Locale;
51 import java.util.UUID;
52 import java.util.regex.Matcher;
53 import java.util.regex.Pattern;
55 import static net.ktnx.mobileledger.utils.Logger.debug;
57 @Database(version = DB.REVISION,
58 entities = {TemplateHeader.class, TemplateAccount.class, Currency.class, Account.class,
59 Profile.class, Option.class, AccountValue.class, Transaction.class,
60 TransactionAccount.class
62 abstract public class DB extends RoomDatabase {
63 public static final int REVISION = 66;
64 public static final String DB_NAME = "MoLe.db";
65 public static final MutableLiveData<Boolean> initComplete = new MutableLiveData<>(false);
66 private static DB instance;
67 private static void fixTransactionDescriptionUpper(
68 @NonNull @NotNull SupportSQLiteDatabase database) {
69 try (Cursor c = database.query("SELECT id, description FROM transactions")) {
70 while (c.moveToNext()) {
71 final long id = c.getLong(0);
72 final String description = c.getString(1);
73 database.execSQL("UPDATE transactions SET description_uc=? WHERE id=?",
74 new Object[]{description.toUpperCase(), id
79 public static DB get() {
82 synchronized (DB.class) {
86 RoomDatabase.Builder<DB> builder =
87 Room.databaseBuilder(App.instance, DB.class, DB_NAME);
88 builder.addMigrations(
89 new Migration[]{singleVersionMigration(17), singleVersionMigration(18),
90 singleVersionMigration(19), singleVersionMigration(20),
91 multiVersionMigration(20, 22), multiVersionMigration(22, 30),
92 multiVersionMigration(30, 32), multiVersionMigration(32, 34),
93 multiVersionMigration(34, 40), singleVersionMigration(41),
94 multiVersionMigration(41, 58), singleVersionMigration(59),
95 singleVersionMigration(60), singleVersionMigration(61),
96 singleVersionMigration(62), singleVersionMigration(63),
97 singleVersionMigration(64), new Migration(64, 65) {
99 public void migrate(@NonNull @NotNull SupportSQLiteDatabase database) {
100 fixTransactionDescriptionUpper(database);
102 }, new Migration(64, 66) {
104 public void migrate(@NonNull @NotNull SupportSQLiteDatabase database) {
105 fixTransactionDescriptionUpper(database);
107 }, new Migration(65, 66) {
109 public void migrate(@NonNull @NotNull SupportSQLiteDatabase database) {
110 fixTransactionDescriptionUpper(database);
114 .addCallback(new Callback() {
116 public void onOpen(@NonNull SupportSQLiteDatabase db) {
118 db.execSQL("PRAGMA foreign_keys = ON");
119 db.execSQL("pragma case_sensitive_like" + "=ON;");
124 // if (BuildConfig.DEBUG)
125 // builder.setQueryCallback(((sqlQuery, bindArgs) -> Logger.debug("room", sqlQuery)),
126 // Executors.newSingleThreadExecutor());
128 return instance = builder.build();
131 private static Migration singleVersionMigration(int toVersion) {
132 return new Migration(toVersion - 1, toVersion) {
134 public void migrate(@NonNull SupportSQLiteDatabase db) {
135 String fileName = String.format(Locale.US, "db_%d", toVersion);
137 applyRevisionFile(db, fileName);
139 // when migrating to version 59, migrate profile/theme options to the
141 if (toVersion == 59) {
142 try (Cursor c = db.query(
143 "SELECT p.id, p.theme FROM profiles p WHERE p.id=(SELECT o.value " +
144 "FROM options o WHERE o.profile_id=0 AND o.name=?)",
145 new Object[]{"profile_id"}))
147 if (c.moveToFirst()) {
148 long currentProfileId = c.getLong(0);
149 int currentTheme = c.getInt(1);
151 if (currentProfileId >= 0 && currentTheme >= 0) {
152 App.storeStartupProfileAndTheme(currentProfileId, currentTheme);
157 if (toVersion == 63) {
158 try (Cursor c = db.query("SELECT id FROM templates")) {
159 while (c.moveToNext()) {
160 db.execSQL("UPDATE templates SET uuid=? WHERE id=?",
161 new Object[]{UUID.randomUUID().toString(), c.getLong(0)});
168 private static Migration dummyVersionMigration(int toVersion) {
169 return new Migration(toVersion - 1, toVersion) {
171 public void migrate(@NonNull SupportSQLiteDatabase db) {
173 String.format(Locale.ROOT, "Dummy DB migration to version %d", toVersion));
177 private static Migration multiVersionMigration(int fromVersion, int toVersion) {
178 return new Migration(fromVersion, toVersion) {
180 public void migrate(@NonNull SupportSQLiteDatabase db) {
181 String fileName = String.format(Locale.US, "db_%d_%d", fromVersion, toVersion);
183 applyRevisionFile(db, fileName);
187 public static void applyRevisionFile(@NonNull SupportSQLiteDatabase db, String fileName) {
188 final Resources rm = App.instance.getResources();
189 int res_id = rm.getIdentifier(fileName, "raw", App.instance.getPackageName());
191 throw new SQLException(String.format(Locale.US, "No resource for %s", fileName));
193 try (InputStream res = rm.openRawResource(res_id)) {
194 debug("db", "Applying " + fileName);
195 InputStreamReader isr = new InputStreamReader(res);
196 BufferedReader reader = new BufferedReader(isr);
198 Pattern endOfStatement = Pattern.compile(";\\s*(?:--.*)?$");
201 String sqlStatement = null;
203 while ((line = reader.readLine()) != null) {
205 if (line.startsWith("--"))
210 if (sqlStatement == null)
213 sqlStatement = sqlStatement.concat(" " + line);
215 Matcher m = endOfStatement.matcher(line);
220 db.execSQL(sqlStatement);
223 catch (Exception e) {
224 throw new RuntimeException(
225 String.format("Error applying %s, line %d, statement: %s", fileName,
226 lineNo, sqlStatement), e);
230 if (sqlStatement != null)
231 throw new RuntimeException(String.format(
232 "Error applying %s: EOF after continuation. Line %s, Incomplete " +
233 "statement: %s", fileName, lineNo, sqlStatement));
236 catch (IOException e) {
237 throw new RuntimeException(String.format("Error opening raw resource for %s", fileName),
241 public abstract TemplateHeaderDAO getTemplateDAO();
243 public abstract TemplateAccountDAO getTemplateAccountDAO();
245 public abstract CurrencyDAO getCurrencyDAO();
247 public abstract AccountDAO getAccountDAO();
249 public abstract AccountValueDAO getAccountValueDAO();
251 public abstract TransactionDAO getTransactionDAO();
253 public abstract TransactionAccountDAO getTransactionAccountDAO();
255 public abstract OptionDAO getOptionDAO();
257 public abstract ProfileDAO getProfileDAO();
259 @androidx.room.Transaction
260 public void deleteAllSync() {
261 getTransactionAccountDAO().deleteAllSync();
262 getTransactionDAO().deleteAllSync();
263 getAccountValueDAO().deleteAllSync();
264 getAccountDAO().deleteAllSync();
265 getTemplateAccountDAO().deleteAllSync();
266 getTemplateDAO().deleteAllSync();
267 getCurrencyDAO().deleteAllSync();
268 getOptionDAO().deleteAllSync();
269 getProfileDAO().deleteAllSync();