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