]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/db/DB.java
DB revision 66: re-calculate descriptionUpper to fix searching
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / db / DB.java
1 /*
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.ktnx.mobileledger.db;
19
20 import android.content.res.Resources;
21 import android.database.Cursor;
22 import android.database.SQLException;
23
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;
31
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;
43
44 import org.jetbrains.annotations.NotNull;
45
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;
54
55 import static net.ktnx.mobileledger.utils.Logger.debug;
56
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
61           })
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
75                         });
76             }
77         }
78     }
79     public static DB get() {
80         if (instance != null)
81             return instance;
82         synchronized (DB.class) {
83             if (instance != null)
84                 return instance;
85
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) {
98                         @Override
99                         public void migrate(@NonNull @NotNull SupportSQLiteDatabase database) {
100                             fixTransactionDescriptionUpper(database);
101                         }
102                     }, new Migration(64, 66) {
103                         @Override
104                         public void migrate(@NonNull @NotNull SupportSQLiteDatabase database) {
105                             fixTransactionDescriptionUpper(database);
106                         }
107                     }, new Migration(65, 66) {
108                         @Override
109                         public void migrate(@NonNull @NotNull SupportSQLiteDatabase database) {
110                             fixTransactionDescriptionUpper(database);
111                         }
112                     }
113                     })
114                    .addCallback(new Callback() {
115                        @Override
116                        public void onOpen(@NonNull SupportSQLiteDatabase db) {
117                            super.onOpen(db);
118                            db.execSQL("PRAGMA foreign_keys = ON");
119                            db.execSQL("pragma case_sensitive_like" + "=ON;");
120
121                        }
122                    });
123
124 //            if (BuildConfig.DEBUG)
125 //                builder.setQueryCallback(((sqlQuery, bindArgs) -> Logger.debug("room", sqlQuery)),
126 //                        Executors.newSingleThreadExecutor());
127
128             return instance = builder.build();
129         }
130     }
131     private static Migration singleVersionMigration(int toVersion) {
132         return new Migration(toVersion - 1, toVersion) {
133             @Override
134             public void migrate(@NonNull SupportSQLiteDatabase db) {
135                 String fileName = String.format(Locale.US, "db_%d", toVersion);
136
137                 applyRevisionFile(db, fileName);
138
139                 // when migrating to version 59, migrate profile/theme options to the
140                 // SharedPreferences
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"}))
146                     {
147                         if (c.moveToFirst()) {
148                             long currentProfileId = c.getLong(0);
149                             int currentTheme = c.getInt(1);
150
151                             if (currentProfileId >= 0 && currentTheme >= 0) {
152                                 App.storeStartupProfileAndTheme(currentProfileId, currentTheme);
153                             }
154                         }
155                     }
156                 }
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)});
162                         }
163                     }
164                 }
165             }
166         };
167     }
168     private static Migration dummyVersionMigration(int toVersion) {
169         return new Migration(toVersion - 1, toVersion) {
170             @Override
171             public void migrate(@NonNull SupportSQLiteDatabase db) {
172                 Logger.debug("db",
173                         String.format(Locale.ROOT, "Dummy DB migration to version %d", toVersion));
174             }
175         };
176     }
177     private static Migration multiVersionMigration(int fromVersion, int toVersion) {
178         return new Migration(fromVersion, toVersion) {
179             @Override
180             public void migrate(@NonNull SupportSQLiteDatabase db) {
181                 String fileName = String.format(Locale.US, "db_%d_%d", fromVersion, toVersion);
182
183                 applyRevisionFile(db, fileName);
184             }
185         };
186     }
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());
190         if (res_id == 0)
191             throw new SQLException(String.format(Locale.US, "No resource for %s", fileName));
192
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);
197
198             Pattern endOfStatement = Pattern.compile(";\\s*(?:--.*)?$");
199
200             String line;
201             String sqlStatement = null;
202             int lineNo = 0;
203             while ((line = reader.readLine()) != null) {
204                 lineNo++;
205                 if (line.startsWith("--"))
206                     continue;
207                 if (line.isEmpty())
208                     continue;
209
210                 if (sqlStatement == null)
211                     sqlStatement = line;
212                 else
213                     sqlStatement = sqlStatement.concat(" " + line);
214
215                 Matcher m = endOfStatement.matcher(line);
216                 if (!m.find())
217                     continue;
218
219                 try {
220                     db.execSQL(sqlStatement);
221                     sqlStatement = null;
222                 }
223                 catch (Exception e) {
224                     throw new RuntimeException(
225                             String.format("Error applying %s, line %d, statement: %s", fileName,
226                                     lineNo, sqlStatement), e);
227                 }
228             }
229
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));
234
235         }
236         catch (IOException e) {
237             throw new RuntimeException(String.format("Error opening raw resource for %s", fileName),
238                     e);
239         }
240     }
241     public abstract TemplateHeaderDAO getTemplateDAO();
242
243     public abstract TemplateAccountDAO getTemplateAccountDAO();
244
245     public abstract CurrencyDAO getCurrencyDAO();
246
247     public abstract AccountDAO getAccountDAO();
248
249     public abstract AccountValueDAO getAccountValueDAO();
250
251     public abstract TransactionDAO getTransactionDAO();
252
253     public abstract TransactionAccountDAO getTransactionAccountDAO();
254
255     public abstract OptionDAO getOptionDAO();
256
257     public abstract ProfileDAO getProfileDAO();
258
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();
270     }
271 }