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