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