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