]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/db/DB.java
add uuid to templates
[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 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.UUID;
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, Transaction.class,
58                       TransactionAccount.class
59           })
60 abstract public class DB extends RoomDatabase {
61     public static final int REVISION = 63;
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             RoomDatabase.Builder<DB> builder =
73                     Room.databaseBuilder(App.instance, DB.class, DB_NAME);
74             builder.addMigrations(
75                     new Migration[]{singleVersionMigration(17), singleVersionMigration(18),
76                                     singleVersionMigration(19), singleVersionMigration(20),
77                                     multiVersionMigration(20, 22), multiVersionMigration(22, 30),
78                                     multiVersionMigration(30, 32), multiVersionMigration(32, 34),
79                                     multiVersionMigration(34, 40), singleVersionMigration(41),
80                                     multiVersionMigration(41, 58), singleVersionMigration(59),
81                                     singleVersionMigration(60), singleVersionMigration(61),
82                                     singleVersionMigration(62), singleVersionMigration(63)
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
94 //            if (BuildConfig.DEBUG)
95 //                builder.setQueryCallback(((sqlQuery, bindArgs) -> Logger.debug("room", sqlQuery)),
96 //                        Executors.newSingleThreadExecutor());
97
98             return instance = builder.build();
99         }
100     }
101     private static Migration singleVersionMigration(int toVersion) {
102         return new Migration(toVersion - 1, toVersion) {
103             @Override
104             public void migrate(@NonNull SupportSQLiteDatabase db) {
105                 String fileName = String.format(Locale.US, "db_%d", toVersion);
106
107                 applyRevisionFile(db, fileName);
108
109                 // when migrating to version 59, migrate profile/theme options to the
110                 // SharedPreferences
111                 if (toVersion == 59) {
112                     try (Cursor c = db.query(
113                             "SELECT p.id, p.theme FROM profiles p WHERE p.id=(SELECT o.value " +
114                             "FROM options o WHERE o.profile_id=0 AND o.name=?)",
115                             new Object[]{"profile_id"}))
116                     {
117                         if (c.moveToFirst()) {
118                             long currentProfileId = c.getLong(0);
119                             int currentTheme = c.getInt(1);
120
121                             if (currentProfileId >= 0 && currentTheme >= 0) {
122                                 App.storeStartupProfileAndTheme(currentProfileId, currentTheme);
123                             }
124                         }
125                     }
126                 }
127                 if (toVersion == 63) {
128                     try (Cursor c = db.query("SELECT id FROM templates")) {
129                         while (c.moveToNext()) {
130                             db.execSQL("UPDATE templates SET uuid=? WHERE id=?",
131                                     new Object[]{UUID.randomUUID().toString(), c.getLong(0)});
132                         }
133                     }
134                 }
135             }
136         };
137     }
138     private static Migration dummyVersionMigration(int toVersion) {
139         return new Migration(toVersion - 1, toVersion) {
140             @Override
141             public void migrate(@NonNull SupportSQLiteDatabase db) {
142                 Logger.debug("db",
143                         String.format(Locale.ROOT, "Dummy DB migration to version %d", toVersion));
144             }
145         };
146     }
147     private static Migration multiVersionMigration(int fromVersion, int toVersion) {
148         return new Migration(fromVersion, toVersion) {
149             @Override
150             public void migrate(@NonNull SupportSQLiteDatabase db) {
151                 String fileName = String.format(Locale.US, "db_%d_%d", fromVersion, toVersion);
152
153                 applyRevisionFile(db, fileName);
154             }
155         };
156     }
157     public static void applyRevisionFile(@NonNull SupportSQLiteDatabase db, String fileName) {
158         final Resources rm = App.instance.getResources();
159         int res_id = rm.getIdentifier(fileName, "raw", App.instance.getPackageName());
160         if (res_id == 0)
161             throw new SQLException(String.format(Locale.US, "No resource for %s", fileName));
162
163         try (InputStream res = rm.openRawResource(res_id)) {
164             debug("db", "Applying " + fileName);
165             InputStreamReader isr = new InputStreamReader(res);
166             BufferedReader reader = new BufferedReader(isr);
167
168             Pattern endOfStatement = Pattern.compile(";\\s*(?:--.*)?$");
169
170             String line;
171             String sqlStatement = null;
172             int lineNo = 0;
173             while ((line = reader.readLine()) != null) {
174                 lineNo++;
175                 if (line.startsWith("--"))
176                     continue;
177                 if (line.isEmpty())
178                     continue;
179
180                 if (sqlStatement == null)
181                     sqlStatement = line;
182                 else
183                     sqlStatement = sqlStatement.concat(" " + line);
184
185                 Matcher m = endOfStatement.matcher(line);
186                 if (!m.find())
187                     continue;
188
189                 try {
190                     db.execSQL(sqlStatement);
191                     sqlStatement = null;
192                 }
193                 catch (Exception e) {
194                     throw new RuntimeException(
195                             String.format("Error applying %s, line %d, statement: %s", fileName,
196                                     lineNo, sqlStatement), e);
197                 }
198             }
199
200             if (sqlStatement != null)
201                 throw new RuntimeException(String.format(
202                         "Error applying %s: EOF after continuation. Line %s, Incomplete " +
203                         "statement: %s", fileName, lineNo, sqlStatement));
204
205         }
206         catch (IOException e) {
207             throw new RuntimeException(String.format("Error opening raw resource for %s", fileName),
208                     e);
209         }
210     }
211     public abstract TemplateHeaderDAO getTemplateDAO();
212
213     public abstract TemplateAccountDAO getTemplateAccountDAO();
214
215     public abstract CurrencyDAO getCurrencyDAO();
216
217     public abstract AccountDAO getAccountDAO();
218
219     public abstract AccountValueDAO getAccountValueDAO();
220
221     public abstract TransactionDAO getTransactionDAO();
222
223     public abstract TransactionAccountDAO getTransactionAccountDAO();
224
225     public abstract OptionDAO getOptionDAO();
226
227     public abstract ProfileDAO getProfileDAO();
228 }