]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/db/DB.java
drop MobileLedgerDatabase, move initComplete to DB
[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.DescriptionHistoryDAO;
37 import net.ktnx.mobileledger.dao.OptionDAO;
38 import net.ktnx.mobileledger.dao.ProfileDAO;
39 import net.ktnx.mobileledger.dao.TemplateAccountDAO;
40 import net.ktnx.mobileledger.dao.TemplateHeaderDAO;
41 import net.ktnx.mobileledger.dao.TransactionAccountDAO;
42 import net.ktnx.mobileledger.dao.TransactionDAO;
43 import net.ktnx.mobileledger.utils.Logger;
44
45 import java.io.BufferedReader;
46 import java.io.IOException;
47 import java.io.InputStream;
48 import java.io.InputStreamReader;
49 import java.util.Locale;
50 import java.util.regex.Matcher;
51 import java.util.regex.Pattern;
52
53 import static net.ktnx.mobileledger.utils.Logger.debug;
54
55 @Database(version = DB.REVISION,
56           entities = {TemplateHeader.class, TemplateAccount.class, Currency.class, Account.class,
57                       Profile.class, Option.class, AccountValue.class, DescriptionHistory.class,
58                       Transaction.class, TransactionAccount.class
59           })
60 abstract public class DB extends RoomDatabase {
61     public static final int REVISION = 59;
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() {
66         if (instance != null)
67             return instance;
68         synchronized (DB.class) {
69             if (instance != null)
70                 return instance;
71
72             return instance = Room.databaseBuilder(App.instance, DB.class, DB_NAME)
73                                   .addMigrations(new Migration[]{singleVersionMigration(17),
74                                                                  singleVersionMigration(18),
75                                                                  singleVersionMigration(19),
76                                                                  singleVersionMigration(20),
77                                                                  multiVersionMigration(20, 22),
78                                                                  multiVersionMigration(22, 30),
79                                                                  multiVersionMigration(30, 32),
80                                                                  multiVersionMigration(32, 34),
81                                                                  multiVersionMigration(34, 40),
82                                                                  singleVersionMigration(41),
83                                                                  multiVersionMigration(41, 58),
84                                                                  singleVersionMigration(59)
85                                   })
86                                   .addCallback(new Callback() {
87                                       @Override
88                                       public void onOpen(@NonNull SupportSQLiteDatabase db) {
89                                           super.onOpen(db);
90                                           db.execSQL("PRAGMA foreign_keys = ON");
91                                           db.execSQL("pragma case_sensitive_like=ON;");
92
93                                       }
94                                   })
95                                   .build();
96         }
97     }
98     private static Migration singleVersionMigration(int toVersion) {
99         return new Migration(toVersion - 1, toVersion) {
100             @Override
101             public void migrate(@NonNull SupportSQLiteDatabase db) {
102                 String fileName = String.format(Locale.US, "db_%d", toVersion);
103
104                 applyRevisionFile(db, fileName);
105
106                 // when migrating to version 59, migrate profile/theme options to the
107                 // SharedPreferences
108                 if (toVersion == 59) {
109                     try (Cursor c = db.query(
110                             "SELECT p.id, p.theme_hue FROM profiles p WHERE p.id=(SELECT o.value " +
111                             "FROM options WHERE o.profile_uid IS NULL AND o.name=?",
112                             new Object[]{"profile_id"}))
113                     {
114                         if (c.moveToFirst()) {
115                             long currentProfileId = c.getLong(0);
116                             int currentTheme = c.getInt(1);
117
118                             if (currentProfileId >= 0 && currentTheme >= 0) {
119                                 App.storeStartupProfileAndTheme(currentProfileId, currentTheme);
120                             }
121                         }
122                     }
123                 }
124             }
125         };
126     }
127     private static Migration dummyVersionMigration(int toVersion) {
128         return new Migration(toVersion - 1, toVersion) {
129             @Override
130             public void migrate(@NonNull SupportSQLiteDatabase db) {
131                 Logger.debug("db",
132                         String.format(Locale.ROOT, "Dummy DB migration to version %d", toVersion));
133             }
134         };
135     }
136     private static Migration multiVersionMigration(int fromVersion, int toVersion) {
137         return new Migration(fromVersion, toVersion) {
138             @Override
139             public void migrate(@NonNull SupportSQLiteDatabase db) {
140                 String fileName = String.format(Locale.US, "db_%d_%d", fromVersion, toVersion);
141
142                 applyRevisionFile(db, fileName);
143             }
144         };
145     }
146     public static void applyRevisionFile(@NonNull SupportSQLiteDatabase db, String fileName) {
147         final Resources rm = App.instance.getResources();
148         int res_id = rm.getIdentifier(fileName, "raw", App.instance.getPackageName());
149         if (res_id == 0)
150             throw new SQLException(String.format(Locale.US, "No resource for %s", fileName));
151
152         try (InputStream res = rm.openRawResource(res_id)) {
153             debug("db", "Applying " + fileName);
154             InputStreamReader isr = new InputStreamReader(res);
155             BufferedReader reader = new BufferedReader(isr);
156
157             Pattern endOfStatement = Pattern.compile(";\\s*(?:--.*)?$");
158
159             String line;
160             String sqlStatement = null;
161             int lineNo = 0;
162             while ((line = reader.readLine()) != null) {
163                 lineNo++;
164                 if (line.startsWith("--"))
165                     continue;
166                 if (line.isEmpty())
167                     continue;
168
169                 if (sqlStatement == null)
170                     sqlStatement = line;
171                 else
172                     sqlStatement = sqlStatement.concat(" " + line);
173
174                 Matcher m = endOfStatement.matcher(line);
175                 if (!m.find())
176                     continue;
177
178                 try {
179                     db.execSQL(sqlStatement);
180                     sqlStatement = null;
181                 }
182                 catch (Exception e) {
183                     throw new RuntimeException(
184                             String.format("Error applying %s, line %d, statement: %s", fileName,
185                                     lineNo, sqlStatement), e);
186                 }
187             }
188
189             if (sqlStatement != null)
190                 throw new RuntimeException(String.format(
191                         "Error applying %s: EOF after continuation. Line %s, Incomplete " +
192                         "statement: %s", fileName, lineNo, sqlStatement));
193
194         }
195         catch (IOException e) {
196             throw new RuntimeException(String.format("Error opening raw resource for %s", fileName),
197                     e);
198         }
199     }
200     public abstract TemplateHeaderDAO getTemplateDAO();
201
202     public abstract TemplateAccountDAO getTemplateAccountDAO();
203
204     public abstract CurrencyDAO getCurrencyDAO();
205
206     public abstract AccountDAO getAccountDAO();
207
208     public abstract AccountValueDAO getAccountValueDAO();
209
210     public abstract TransactionDAO getTransactionDAO();
211
212     public abstract TransactionAccountDAO getTransactionAccountDAO();
213
214     public abstract OptionDAO getOptionDAO();
215
216     public abstract DescriptionHistoryDAO getDescriptionHistoryDAO();
217
218     public abstract ProfileDAO getProfileDAO();
219 }