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