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 = 65;
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 public static DB get() {
70 synchronized (DB.class) {
74 RoomDatabase.Builder<DB> builder =
75 Room.databaseBuilder(App.instance, DB.class, DB_NAME);
76 builder.addMigrations(
77 new Migration[]{singleVersionMigration(17), singleVersionMigration(18),
78 singleVersionMigration(19), singleVersionMigration(20),
79 multiVersionMigration(20, 22), multiVersionMigration(22, 30),
80 multiVersionMigration(30, 32), multiVersionMigration(32, 34),
81 multiVersionMigration(34, 40), singleVersionMigration(41),
82 multiVersionMigration(41, 58), singleVersionMigration(59),
83 singleVersionMigration(60), singleVersionMigration(61),
84 singleVersionMigration(62), singleVersionMigration(63),
85 singleVersionMigration(64), new Migration(64, 65) {
87 public void migrate(@NonNull @NotNull SupportSQLiteDatabase database) {
88 try (Cursor c = database.query(
89 "SELECT id, description FROM transactions"))
91 while (c.moveToNext()) {
92 final long id = c.getLong(0);
93 final String description = c.getString(1);
95 "UPDATE transactions SET description_uc=? WHERE id=?",
96 new Object[]{description.toUpperCase(), id
103 .addCallback(new Callback() {
105 public void onOpen(@NonNull SupportSQLiteDatabase db) {
107 db.execSQL("PRAGMA foreign_keys = ON");
108 db.execSQL("pragma case_sensitive_like" + "=ON;");
113 // if (BuildConfig.DEBUG)
114 // builder.setQueryCallback(((sqlQuery, bindArgs) -> Logger.debug("room", sqlQuery)),
115 // Executors.newSingleThreadExecutor());
117 return instance = builder.build();
120 private static Migration singleVersionMigration(int toVersion) {
121 return new Migration(toVersion - 1, toVersion) {
123 public void migrate(@NonNull SupportSQLiteDatabase db) {
124 String fileName = String.format(Locale.US, "db_%d", toVersion);
126 applyRevisionFile(db, fileName);
128 // when migrating to version 59, migrate profile/theme options to the
130 if (toVersion == 59) {
131 try (Cursor c = db.query(
132 "SELECT p.id, p.theme FROM profiles p WHERE p.id=(SELECT o.value " +
133 "FROM options o WHERE o.profile_id=0 AND o.name=?)",
134 new Object[]{"profile_id"}))
136 if (c.moveToFirst()) {
137 long currentProfileId = c.getLong(0);
138 int currentTheme = c.getInt(1);
140 if (currentProfileId >= 0 && currentTheme >= 0) {
141 App.storeStartupProfileAndTheme(currentProfileId, currentTheme);
146 if (toVersion == 63) {
147 try (Cursor c = db.query("SELECT id FROM templates")) {
148 while (c.moveToNext()) {
149 db.execSQL("UPDATE templates SET uuid=? WHERE id=?",
150 new Object[]{UUID.randomUUID().toString(), c.getLong(0)});
157 private static Migration dummyVersionMigration(int toVersion) {
158 return new Migration(toVersion - 1, toVersion) {
160 public void migrate(@NonNull SupportSQLiteDatabase db) {
162 String.format(Locale.ROOT, "Dummy DB migration to version %d", toVersion));
166 private static Migration multiVersionMigration(int fromVersion, int toVersion) {
167 return new Migration(fromVersion, toVersion) {
169 public void migrate(@NonNull SupportSQLiteDatabase db) {
170 String fileName = String.format(Locale.US, "db_%d_%d", fromVersion, toVersion);
172 applyRevisionFile(db, fileName);
176 public static void applyRevisionFile(@NonNull SupportSQLiteDatabase db, String fileName) {
177 final Resources rm = App.instance.getResources();
178 int res_id = rm.getIdentifier(fileName, "raw", App.instance.getPackageName());
180 throw new SQLException(String.format(Locale.US, "No resource for %s", fileName));
182 try (InputStream res = rm.openRawResource(res_id)) {
183 debug("db", "Applying " + fileName);
184 InputStreamReader isr = new InputStreamReader(res);
185 BufferedReader reader = new BufferedReader(isr);
187 Pattern endOfStatement = Pattern.compile(";\\s*(?:--.*)?$");
190 String sqlStatement = null;
192 while ((line = reader.readLine()) != null) {
194 if (line.startsWith("--"))
199 if (sqlStatement == null)
202 sqlStatement = sqlStatement.concat(" " + line);
204 Matcher m = endOfStatement.matcher(line);
209 db.execSQL(sqlStatement);
212 catch (Exception e) {
213 throw new RuntimeException(
214 String.format("Error applying %s, line %d, statement: %s", fileName,
215 lineNo, sqlStatement), e);
219 if (sqlStatement != null)
220 throw new RuntimeException(String.format(
221 "Error applying %s: EOF after continuation. Line %s, Incomplete " +
222 "statement: %s", fileName, lineNo, sqlStatement));
225 catch (IOException e) {
226 throw new RuntimeException(String.format("Error opening raw resource for %s", fileName),
230 public abstract TemplateHeaderDAO getTemplateDAO();
232 public abstract TemplateAccountDAO getTemplateAccountDAO();
234 public abstract CurrencyDAO getCurrencyDAO();
236 public abstract AccountDAO getAccountDAO();
238 public abstract AccountValueDAO getAccountValueDAO();
240 public abstract TransactionDAO getTransactionDAO();
242 public abstract TransactionAccountDAO getTransactionAccountDAO();
244 public abstract OptionDAO getOptionDAO();
246 public abstract ProfileDAO getProfileDAO();
248 @androidx.room.Transaction
249 public void deleteAllSync() {
250 getTransactionAccountDAO().deleteAllSync();
251 getTransactionDAO().deleteAllSync();
252 getAccountValueDAO().deleteAllSync();
253 getAccountDAO().deleteAllSync();
254 getTemplateAccountDAO().deleteAllSync();
255 getTemplateDAO().deleteAllSync();
256 getCurrencyDAO().deleteAllSync();
257 getOptionDAO().deleteAllSync();
258 getProfileDAO().deleteAllSync();