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