]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/db/DB.java
methods for deleting all DB tables
[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 = 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() {
68         if (instance != null)
69             return instance;
70         synchronized (DB.class) {
71             if (instance != null)
72                 return instance;
73
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) {
86                         @Override
87                         public void migrate(@NonNull @NotNull SupportSQLiteDatabase database) {
88                             try (Cursor c = database.query(
89                                     "SELECT id, description FROM transactions"))
90                             {
91                                 while (c.moveToNext()) {
92                                     final long id = c.getLong(0);
93                                     final String description = c.getString(1);
94                                     database.execSQL(
95                                             "UPDATE transactions SET description_uc=? WHERE id=?",
96                                             new Object[]{description.toUpperCase(), id
97                                             });
98                                 }
99                             }
100                         }
101                     }
102                     })
103                    .addCallback(new Callback() {
104                        @Override
105                        public void onOpen(@NonNull SupportSQLiteDatabase db) {
106                            super.onOpen(db);
107                            db.execSQL("PRAGMA foreign_keys = ON");
108                            db.execSQL("pragma case_sensitive_like" + "=ON;");
109
110                        }
111                    });
112
113 //            if (BuildConfig.DEBUG)
114 //                builder.setQueryCallback(((sqlQuery, bindArgs) -> Logger.debug("room", sqlQuery)),
115 //                        Executors.newSingleThreadExecutor());
116
117             return instance = builder.build();
118         }
119     }
120     private static Migration singleVersionMigration(int toVersion) {
121         return new Migration(toVersion - 1, toVersion) {
122             @Override
123             public void migrate(@NonNull SupportSQLiteDatabase db) {
124                 String fileName = String.format(Locale.US, "db_%d", toVersion);
125
126                 applyRevisionFile(db, fileName);
127
128                 // when migrating to version 59, migrate profile/theme options to the
129                 // SharedPreferences
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"}))
135                     {
136                         if (c.moveToFirst()) {
137                             long currentProfileId = c.getLong(0);
138                             int currentTheme = c.getInt(1);
139
140                             if (currentProfileId >= 0 && currentTheme >= 0) {
141                                 App.storeStartupProfileAndTheme(currentProfileId, currentTheme);
142                             }
143                         }
144                     }
145                 }
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)});
151                         }
152                     }
153                 }
154             }
155         };
156     }
157     private static Migration dummyVersionMigration(int toVersion) {
158         return new Migration(toVersion - 1, toVersion) {
159             @Override
160             public void migrate(@NonNull SupportSQLiteDatabase db) {
161                 Logger.debug("db",
162                         String.format(Locale.ROOT, "Dummy DB migration to version %d", toVersion));
163             }
164         };
165     }
166     private static Migration multiVersionMigration(int fromVersion, int toVersion) {
167         return new Migration(fromVersion, toVersion) {
168             @Override
169             public void migrate(@NonNull SupportSQLiteDatabase db) {
170                 String fileName = String.format(Locale.US, "db_%d_%d", fromVersion, toVersion);
171
172                 applyRevisionFile(db, fileName);
173             }
174         };
175     }
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());
179         if (res_id == 0)
180             throw new SQLException(String.format(Locale.US, "No resource for %s", fileName));
181
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);
186
187             Pattern endOfStatement = Pattern.compile(";\\s*(?:--.*)?$");
188
189             String line;
190             String sqlStatement = null;
191             int lineNo = 0;
192             while ((line = reader.readLine()) != null) {
193                 lineNo++;
194                 if (line.startsWith("--"))
195                     continue;
196                 if (line.isEmpty())
197                     continue;
198
199                 if (sqlStatement == null)
200                     sqlStatement = line;
201                 else
202                     sqlStatement = sqlStatement.concat(" " + line);
203
204                 Matcher m = endOfStatement.matcher(line);
205                 if (!m.find())
206                     continue;
207
208                 try {
209                     db.execSQL(sqlStatement);
210                     sqlStatement = null;
211                 }
212                 catch (Exception e) {
213                     throw new RuntimeException(
214                             String.format("Error applying %s, line %d, statement: %s", fileName,
215                                     lineNo, sqlStatement), e);
216                 }
217             }
218
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));
223
224         }
225         catch (IOException e) {
226             throw new RuntimeException(String.format("Error opening raw resource for %s", fileName),
227                     e);
228         }
229     }
230     public abstract TemplateHeaderDAO getTemplateDAO();
231
232     public abstract TemplateAccountDAO getTemplateAccountDAO();
233
234     public abstract CurrencyDAO getCurrencyDAO();
235
236     public abstract AccountDAO getAccountDAO();
237
238     public abstract AccountValueDAO getAccountValueDAO();
239
240     public abstract TransactionDAO getTransactionDAO();
241
242     public abstract TransactionAccountDAO getTransactionAccountDAO();
243
244     public abstract OptionDAO getOptionDAO();
245
246     public abstract ProfileDAO getProfileDAO();
247
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();
259     }
260 }