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