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