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