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.
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.
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/>.
18 package net.ktnx.mobileledger.model;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.res.Resources;
23 import android.database.Cursor;
24 import android.database.sqlite.SQLiteDatabase;
25 import android.os.Bundle;
26 import android.text.TextUtils;
27 import android.util.SparseArray;
29 import androidx.annotation.Nullable;
31 import net.ktnx.mobileledger.App;
32 import net.ktnx.mobileledger.R;
33 import net.ktnx.mobileledger.async.DbOpQueue;
34 import net.ktnx.mobileledger.json.API;
35 import net.ktnx.mobileledger.ui.profiles.ProfileDetailActivity;
36 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
37 import net.ktnx.mobileledger.utils.Logger;
38 import net.ktnx.mobileledger.utils.Misc;
39 import net.ktnx.mobileledger.utils.SimpleDate;
41 import org.jetbrains.annotations.Contract;
43 import java.util.ArrayList;
44 import java.util.HashMap;
45 import java.util.List;
46 import java.util.Locale;
48 import java.util.Objects;
50 import static net.ktnx.mobileledger.utils.Logger.debug;
52 public final class MobileLedgerProfile {
53 // N.B. when adding new fields, update the copy-constructor below
54 private final long id;
56 private boolean permitPosting;
57 private boolean showCommentsByDefault;
58 private boolean showCommodityByDefault;
59 private String defaultCommodity;
60 private String preferredAccountsFilter;
62 private boolean authEnabled;
63 private String authUserName;
64 private String authPassword;
66 private int orderNo = -1;
67 private API apiVersion = API.auto;
68 private FutureDates futureDates = FutureDates.None;
69 private boolean accountsLoaded;
70 private boolean transactionsLoaded;
71 private HledgerVersion detectedVersion;
72 // N.B. when adding new fields, update the copy-constructor below
73 transient private AccountAndTransactionListSaver accountAndTransactionListSaver;
74 public MobileLedgerProfile(long id) {
77 public MobileLedgerProfile(MobileLedgerProfile origin) {
80 permitPosting = origin.permitPosting;
81 showCommentsByDefault = origin.showCommentsByDefault;
82 showCommodityByDefault = origin.showCommodityByDefault;
83 preferredAccountsFilter = origin.preferredAccountsFilter;
85 authEnabled = origin.authEnabled;
86 authUserName = origin.authUserName;
87 authPassword = origin.authPassword;
88 themeHue = origin.themeHue;
89 orderNo = origin.orderNo;
90 futureDates = origin.futureDates;
91 apiVersion = origin.apiVersion;
92 defaultCommodity = origin.defaultCommodity;
93 accountsLoaded = origin.accountsLoaded;
94 transactionsLoaded = origin.transactionsLoaded;
95 if (origin.detectedVersion != null)
96 detectedVersion = new HledgerVersion(origin.detectedVersion);
98 // loads all profiles into Data.profiles
99 // returns the profile with the given UUID
100 public static MobileLedgerProfile loadAllFromDB(long currentProfileId) {
101 MobileLedgerProfile result = null;
102 ArrayList<MobileLedgerProfile> list = new ArrayList<>();
103 SQLiteDatabase db = App.getDatabase();
104 try (Cursor cursor = db.rawQuery("SELECT id, name, url, use_authentication, auth_user, " +
105 "auth_password, permit_posting, theme, order_no, " +
106 "preferred_accounts_filter, future_dates, api_version, " +
107 "show_commodity_by_default, default_commodity, " +
108 "show_comments_by_default, detected_version_pre_1_19, " +
109 "detected_version_major, detected_version_minor FROM " +
110 "profiles order by order_no", null))
112 while (cursor.moveToNext()) {
113 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getLong(0));
114 item.setName(cursor.getString(1));
115 item.setUrl(cursor.getString(2));
116 item.setAuthEnabled(cursor.getInt(3) == 1);
117 item.setAuthUserName(cursor.getString(4));
118 item.setAuthPassword(cursor.getString(5));
119 item.setPostingPermitted(cursor.getInt(6) == 1);
120 item.setThemeId(cursor.getInt(7));
121 item.orderNo = cursor.getInt(8);
122 item.setPreferredAccountsFilter(cursor.getString(9));
123 item.setFutureDates(cursor.getInt(10));
124 item.setApiVersion(cursor.getInt(11));
125 item.setShowCommodityByDefault(cursor.getInt(12) == 1);
126 item.setDefaultCommodity(cursor.getString(13));
127 item.setShowCommentsByDefault(cursor.getInt(14) == 1);
129 boolean pre_1_20 = cursor.getInt(15) == 1;
130 int major = cursor.getInt(16);
131 int minor = cursor.getInt(17);
133 if (!pre_1_20 && major == 0 && minor == 0) {
134 item.detectedVersion = null;
137 item.detectedVersion = new HledgerVersion(true);
140 item.detectedVersion = new HledgerVersion(major, minor);
144 if (item.getId() == currentProfileId)
148 Data.profiles.postValue(list);
151 public static void storeProfilesOrder() {
152 SQLiteDatabase db = App.getDatabase();
153 db.beginTransactionNonExclusive();
156 for (MobileLedgerProfile p : Objects.requireNonNull(Data.profiles.getValue())) {
157 db.execSQL("update profiles set order_no=? where uuid=?",
158 new Object[]{orderNo, p.getId()});
162 db.setTransactionSuccessful();
168 static public void startEditProfileActivity(Context context, MobileLedgerProfile profile) {
169 Intent intent = new Intent(context, ProfileDetailActivity.class);
170 Bundle args = new Bundle();
171 if (profile != null) {
172 int index = Data.getProfileIndex(profile);
174 intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
176 intent.putExtras(args);
177 context.startActivity(intent, args);
179 public HledgerVersion getDetectedVersion() {
180 return detectedVersion;
182 public void setDetectedVersion(HledgerVersion detectedVersion) {
183 this.detectedVersion = detectedVersion;
185 @Contract(value = "null -> false", pure = true)
187 public boolean equals(@Nullable Object obj) {
192 if (obj.getClass() != this.getClass())
195 MobileLedgerProfile p = (MobileLedgerProfile) obj;
198 if (!name.equals(p.name))
200 if (permitPosting != p.permitPosting)
202 if (showCommentsByDefault != p.showCommentsByDefault)
204 if (showCommodityByDefault != p.showCommodityByDefault)
206 if (!Objects.equals(defaultCommodity, p.defaultCommodity))
208 if (!Objects.equals(preferredAccountsFilter, p.preferredAccountsFilter))
210 if (!Objects.equals(url, p.url))
212 if (authEnabled != p.authEnabled)
214 if (!Objects.equals(authUserName, p.authUserName))
216 if (!Objects.equals(authPassword, p.authPassword))
218 if (themeHue != p.themeHue)
220 if (apiVersion != p.apiVersion)
222 if (!Objects.equals(detectedVersion, p.detectedVersion))
224 return futureDates == p.futureDates;
226 public boolean getShowCommentsByDefault() {
227 return showCommentsByDefault;
229 public void setShowCommentsByDefault(boolean newValue) {
230 this.showCommentsByDefault = newValue;
232 public boolean getShowCommodityByDefault() {
233 return showCommodityByDefault;
235 public void setShowCommodityByDefault(boolean showCommodityByDefault) {
236 this.showCommodityByDefault = showCommodityByDefault;
238 public String getDefaultCommodity() {
239 return defaultCommodity;
241 public void setDefaultCommodity(String defaultCommodity) {
242 this.defaultCommodity = defaultCommodity;
244 public void setDefaultCommodity(CharSequence defaultCommodity) {
245 if (defaultCommodity == null)
246 this.defaultCommodity = null;
248 this.defaultCommodity = String.valueOf(defaultCommodity);
250 public API getApiVersion() {
253 public void setApiVersion(API apiVersion) {
254 this.apiVersion = apiVersion;
256 public void setApiVersion(int apiVersion) {
257 this.apiVersion = API.valueOf(apiVersion);
259 public FutureDates getFutureDates() {
262 public void setFutureDates(int anInt) {
263 futureDates = FutureDates.valueOf(anInt);
265 public void setFutureDates(FutureDates futureDates) {
266 this.futureDates = futureDates;
268 public String getPreferredAccountsFilter() {
269 return preferredAccountsFilter;
271 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
272 this.preferredAccountsFilter = preferredAccountsFilter;
274 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
275 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
277 public boolean isPostingPermitted() {
278 return permitPosting;
280 public void setPostingPermitted(boolean permitPosting) {
281 this.permitPosting = permitPosting;
283 public long getId() {
286 public String getName() {
289 public void setName(CharSequence text) {
290 setName(String.valueOf(text));
292 public void setName(String name) {
295 public String getUrl() {
298 public void setUrl(CharSequence text) {
299 setUrl(String.valueOf(text));
301 public void setUrl(String url) {
304 public boolean isAuthEnabled() {
307 public void setAuthEnabled(boolean authEnabled) {
308 this.authEnabled = authEnabled;
310 public String getAuthUserName() {
313 public void setAuthUserName(CharSequence text) {
314 setAuthUserName(String.valueOf(text));
316 public void setAuthUserName(String authUserName) {
317 this.authUserName = authUserName;
319 public String getAuthPassword() {
322 public void setAuthPassword(CharSequence text) {
323 setAuthPassword(String.valueOf(text));
325 public void setAuthPassword(String authPassword) {
326 this.authPassword = authPassword;
328 public void storeInDB() {
329 SQLiteDatabase db = App.getDatabase();
330 db.beginTransactionNonExclusive();
332 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
333 // "url=%s, permit_posting=%s, authEnabled=%s, " +
334 // "themeHue=%d", uuid, name, url,
335 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeHue));
336 db.execSQL("REPLACE INTO profiles(id, name, permit_posting, url, " +
337 "use_authentication, auth_user, auth_password, theme, order_no, " +
338 "preferred_accounts_filter, future_dates, api_version, " +
339 "show_commodity_by_default, default_commodity, show_comments_by_default," +
340 "detected_version_pre_1_19, detected_version_major, " +
341 "detected_version_minor) " +
342 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
343 new Object[]{id, name, permitPosting, url, authEnabled,
344 authEnabled ? authUserName : null,
345 authEnabled ? authPassword : null, themeHue, orderNo,
346 preferredAccountsFilter, futureDates.toInt(), apiVersion.toInt(),
347 showCommodityByDefault, defaultCommodity, showCommentsByDefault,
348 (detectedVersion != null) && detectedVersion.isPre_1_20_1(),
349 (detectedVersion == null) ? 0 : detectedVersion.getMajor(),
350 (detectedVersion == null) ? 0 : detectedVersion.getMinor()
352 db.setTransactionSuccessful();
358 public void storeAccount(SQLiteDatabase db, int generation, LedgerAccount acc,
359 boolean storeUiFields) {
360 // replace into is a bad idea because it would reset hidden to its default value
361 // we like the default, but for new accounts only
362 String sql = "update accounts set generation = ?";
363 List<Object> params = new ArrayList<>();
364 params.add(generation);
366 sql += ", expanded=?";
367 params.add(acc.isExpanded() ? 1 : 0);
369 sql += " where profile_id=? and name=?";
371 params.add(acc.getName());
372 db.execSQL(sql, params.toArray());
374 db.execSQL("insert into accounts(profile_id, name, name_upper, parent_name, level, " +
375 "expanded, generation) select ?,?,?,?,?,0,? where (select changes() = 0)",
376 new Object[]{id, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
377 acc.getLevel(), generation
379 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
381 public void storeAccountValue(SQLiteDatabase db, int generation, String name, String currency,
383 if (!TextUtils.isEmpty(currency)) {
385 try (Cursor c = db.rawQuery("select 1 from currencies where name=?",
386 new String[]{currency}))
388 exists = c.moveToFirst();
392 "insert into currencies(id, name, position, has_gap) values((select max" +
393 "(id) from currencies)+1, ?, ?, ?)", new Object[]{currency,
394 Objects.requireNonNull(
395 Data.currencySymbolPosition.getValue()).toString(),
396 Data.currencyGap.getValue()
401 long accId = findAddAccount(db, name);
403 db.execSQL("replace into account_values(account_id, " +
404 "currency, value, generation) values(?, ?, ?, ?);",
405 new Object[]{accId, Misc.emptyIsNull(currency), amount, generation});
407 private long findAddAccount(SQLiteDatabase db, String accountName) {
408 try (Cursor c = db.rawQuery("select id from accounts where profile_id=? and name=?",
409 new String[]{String.valueOf(id), accountName}))
416 try (Cursor c = db.rawQuery(
417 "insert into accounts(profile_id, name, name_upper) values(?, ?, ?) returning id",
418 new String[]{String.valueOf(id), accountName, accountName.toUpperCase()}))
424 public void storeTransaction(SQLiteDatabase db, int generation, LedgerTransaction tr) {
426 // Logger.debug("storeTransaction", String.format(Locale.US, "ID %d", tr.getId()));
427 SimpleDate d = tr.getDate();
428 db.execSQL("UPDATE transactions SET year=?, month=?, day=?, description=?, comment=?, " +
429 "data_hash=?, generation=? WHERE profile_id=? AND ledger_id=?",
430 new Object[]{d.year, d.month, d.day, tr.getDescription(), tr.getComment(),
431 tr.getDataHash(), generation, id, tr.getId()
434 "INSERT INTO transactions(profile_id, ledger_id, year, month, day, description, " +
435 "comment, data_hash, generation) " +
436 "select ?,?,?,?,?,?,?,?,? WHERE (select changes() = 0)",
437 new Object[]{id, tr.getId(), tr.getDate().year, tr.getDate().month,
438 tr.getDate().day, tr.getDescription(), tr.getComment(),
439 tr.getDataHash(), generation
442 int accountOrderNo = 1;
443 for (LedgerTransactionAccount item : tr.getAccounts()) {
444 db.execSQL("UPDATE transaction_accounts SET account_name=?, amount=?, currency=?, " +
445 "comment=?, generation=? " + "WHERE transaction_id=? AND order_no=?",
446 new Object[]{item.getAccountName(), item.getAmount(),
447 Misc.nullIsEmpty(item.getCurrency()), item.getComment(),
448 generation, tr.getId(), accountOrderNo
450 db.execSQL("INSERT INTO transaction_accounts(transaction_id, " +
451 "order_no, account_name, amount, currency, comment, generation) " +
452 "select ?, ?, ?, ?, ?, ?, ? WHERE (select changes() = 0)",
453 new Object[]{tr.getId(), accountOrderNo, item.getAccountName(),
454 item.getAmount(), Misc.nullIsEmpty(item.getCurrency()),
455 item.getComment(), generation
460 // debug("profile", String.format("Transaction %d stored", tr.getId()));
462 public String getOption(String name, String default_value) {
463 SQLiteDatabase db = App.getDatabase();
464 try (Cursor cursor = db.rawQuery(
465 "select value from options where profile_id = ? and name=?",
466 new String[]{String.valueOf(id), name}))
468 if (cursor.moveToFirst()) {
469 String result = cursor.getString(0);
471 if (result == null) {
472 debug("profile", "returning default value for " + name);
473 result = default_value;
476 debug("profile", String.format("option %s=%s", name, result));
481 return default_value;
483 catch (Exception e) {
484 debug("db", "returning default value for " + name, e);
485 return default_value;
488 public long getLongOption(String name, long default_value) {
490 String result = getOption(name, "");
491 if ((result == null) || result.isEmpty()) {
492 debug("profile", String.format("Returning default value for option %s", name));
493 longResult = default_value;
497 longResult = Long.parseLong(result);
498 debug("profile", String.format("option %s=%s", name, result));
500 catch (Exception e) {
501 debug("profile", String.format("Returning default value for option %s", name), e);
502 longResult = default_value;
508 public void setOption(String name, String value) {
509 debug("profile", String.format("setting option %s=%s", name, value));
510 DbOpQueue.add("insert or replace into options(profile_id, name, value) values(?, ?, ?);",
511 new String[]{String.valueOf(id), name, value});
513 public void setLongOption(String name, long value) {
514 setOption(name, String.valueOf(value));
516 public void removeFromDB() {
517 SQLiteDatabase db = App.getDatabase();
518 debug("db", String.format(Locale.ROOT, "removing profile %d from DB", id));
519 db.beginTransactionNonExclusive();
521 Object[] id_param = new Object[]{id};
522 db.execSQL("delete from transactions where profile_id=?", id_param);
523 db.execSQL("delete from accounts where profile=?", id_param);
524 db.execSQL("delete from options where profile=?", id_param);
525 db.execSQL("delete from profiles where id=?", id_param);
526 db.setTransactionSuccessful();
532 public LedgerTransaction loadTransaction(int transactionId) {
533 LedgerTransaction tr = new LedgerTransaction(transactionId, this.id);
534 tr.loadData(App.getDatabase());
538 public int getThemeHue() {
539 // debug("profile", String.format("Profile.getThemeHue() returning %d", themeHue));
540 return this.themeHue;
542 public void setThemeHue(Object o) {
543 setThemeId(Integer.parseInt(String.valueOf(o)));
545 public void setThemeId(int themeHue) {
546 // debug("profile", String.format("Profile.setThemeHue(%d) called", themeHue));
547 this.themeHue = themeHue;
549 public int getNextTransactionsGeneration(SQLiteDatabase db) {
550 try (Cursor c = db.rawQuery(
551 "SELECT generation FROM transactions WHERE profile_id=? LIMIT 1",
552 new String[]{String.valueOf(id)}))
555 return c.getInt(0) + 1;
559 private int getNextAccountsGeneration(SQLiteDatabase db) {
560 try (Cursor c = db.rawQuery("SELECT generation FROM accounts WHERE profile_id=? LIMIT 1",
561 new String[]{String.valueOf(id)})) {
563 return c.getInt(0) + 1;
567 private void deleteNotPresentAccounts(SQLiteDatabase db, int generation) {
568 Logger.debug("db/benchmark", "Deleting obsolete accounts");
569 db.execSQL("DELETE FROM account_values WHERE profile=? AND generation <> ?",
570 new Object[]{id, generation});
571 db.execSQL("DELETE FROM accounts WHERE profile=? AND generation <> ?",
572 new Object[]{id, generation});
573 Logger.debug("db/benchmark", "Done deleting obsolete accounts");
575 private void deleteNotPresentTransactions(SQLiteDatabase db, int generation) {
576 Logger.debug("db/benchmark", "Deleting obsolete transactions");
577 db.execSQL("DELETE FROM transaction_accounts WHERE profile=? AND generation <> ?",
578 new Object[]{id, generation});
579 db.execSQL("DELETE FROM transactions WHERE profile=? AND generation <> ?",
580 new Object[]{id, generation});
581 Logger.debug("db/benchmark", "Done deleting obsolete transactions");
583 public void wipeAllData() {
584 SQLiteDatabase db = App.getDatabase();
585 db.beginTransaction();
587 String[] pUuid = new String[]{String.valueOf(id)};
588 db.execSQL("delete from options where profile=?", pUuid);
589 db.execSQL("delete from accounts where profile=?", pUuid);
590 db.execSQL("delete from account_values where profile=?", pUuid);
591 db.execSQL("delete from transactions where profile=?", pUuid);
592 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
593 db.setTransactionSuccessful();
594 debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));
600 public List<Currency> getCurrencies() {
601 SQLiteDatabase db = App.getDatabase();
603 ArrayList<Currency> result = new ArrayList<>();
605 try (Cursor c = db.rawQuery("SELECT c.id, c.name, c.position, c.has_gap FROM currencies c",
608 while (c.moveToNext()) {
609 Currency currency = new Currency(c.getInt(0), c.getString(1),
610 Currency.Position.valueOf(c.getString(2)), c.getInt(3) == 1);
611 result.add(currency);
617 Currency loadCurrencyByName(String name) {
618 SQLiteDatabase db = App.getDatabase();
619 Currency result = tryLoadCurrencyByName(db, name);
621 throw new RuntimeException(String.format("Unable to load currency '%s'", name));
624 private Currency tryLoadCurrencyByName(SQLiteDatabase db, String name) {
625 try (Cursor cursor = db.rawQuery(
626 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.name=?",
629 if (cursor.moveToFirst()) {
630 return new Currency(cursor.getInt(0), cursor.getString(1),
631 Currency.Position.valueOf(cursor.getString(2)), cursor.getInt(3) == 1);
636 public void storeAccountAndTransactionListAsync(List<LedgerAccount> accounts,
637 List<LedgerTransaction> transactions) {
638 if (accountAndTransactionListSaver != null)
639 accountAndTransactionListSaver.interrupt();
641 accountAndTransactionListSaver =
642 new AccountAndTransactionListSaver(this, accounts, transactions);
643 accountAndTransactionListSaver.start();
645 private Currency tryLoadCurrencyById(SQLiteDatabase db, int id) {
646 try (Cursor cursor = db.rawQuery(
647 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.id=?",
648 new String[]{String.valueOf(id)}))
650 if (cursor.moveToFirst()) {
651 return new Currency(cursor.getInt(0), cursor.getString(1),
652 Currency.Position.valueOf(cursor.getString(2)), cursor.getInt(3) == 1);
657 public Currency loadCurrencyById(int id) {
658 SQLiteDatabase db = App.getDatabase();
659 Currency result = tryLoadCurrencyById(db, id);
661 throw new RuntimeException(String.format("Unable to load currency with id '%d'", id));
665 public enum FutureDates {
666 None(0), OneWeek(7), TwoWeeks(14), OneMonth(30), TwoMonths(60), ThreeMonths(90),
667 SixMonths(180), OneYear(365), All(-1);
668 private static final SparseArray<FutureDates> map = new SparseArray<>();
671 for (FutureDates item : FutureDates.values()) {
672 map.put(item.value, item);
676 private final int value;
677 FutureDates(int value) {
680 public static FutureDates valueOf(int i) {
681 return map.get(i, None);
686 public String getText(Resources resources) {
689 return resources.getString(R.string.future_dates_7);
691 return resources.getString(R.string.future_dates_14);
693 return resources.getString(R.string.future_dates_30);
695 return resources.getString(R.string.future_dates_60);
697 return resources.getString(R.string.future_dates_90);
699 return resources.getString(R.string.future_dates_180);
701 return resources.getString(R.string.future_dates_365);
703 return resources.getString(R.string.future_dates_all);
705 return resources.getString(R.string.future_dates_none);
710 private static class AccountAndTransactionListSaver extends Thread {
711 private final MobileLedgerProfile profile;
712 private final List<LedgerAccount> accounts;
713 private final List<LedgerTransaction> transactions;
714 AccountAndTransactionListSaver(MobileLedgerProfile profile, List<LedgerAccount> accounts,
715 List<LedgerTransaction> transactions) {
716 this.accounts = accounts;
717 this.transactions = transactions;
718 this.profile = profile;
720 public int getNextDescriptionsGeneration(SQLiteDatabase db) {
722 try (Cursor c = db.rawQuery("SELECT generation FROM description_history LIMIT 1",
725 if (c.moveToFirst()) {
726 generation = c.getInt(0) + 1;
731 void deleteNotPresentDescriptions(SQLiteDatabase db, int generation) {
732 Logger.debug("db/benchmark", "Deleting obsolete descriptions");
733 db.execSQL("DELETE FROM description_history WHERE generation <> ?",
734 new Object[]{generation});
735 db.execSQL("DELETE FROM description_history WHERE generation <> ?",
736 new Object[]{generation});
737 Logger.debug("db/benchmark", "Done deleting obsolete descriptions");
741 SQLiteDatabase db = App.getDatabase();
742 db.beginTransactionNonExclusive();
744 int accountsGeneration = profile.getNextAccountsGeneration(db);
748 int transactionsGeneration = profile.getNextTransactionsGeneration(db);
752 for (LedgerAccount acc : accounts) {
753 profile.storeAccount(db, accountsGeneration, acc, false);
756 for (LedgerAmount amt : acc.getAmounts()) {
757 profile.storeAccountValue(db, accountsGeneration, acc.getName(),
758 amt.getCurrency(), amt.getAmount());
764 for (LedgerTransaction tr : transactions) {
765 profile.storeTransaction(db, transactionsGeneration, tr);
770 profile.deleteNotPresentTransactions(db, transactionsGeneration);
771 if (isInterrupted()) {
774 profile.deleteNotPresentAccounts(db, accountsGeneration);
778 Map<String, Boolean> unique = new HashMap<>();
780 debug("descriptions", "Starting refresh");
781 int descriptionsGeneration = getNextDescriptionsGeneration(db);
782 try (Cursor c = db.rawQuery("SELECT distinct description from transactions",
785 while (c.moveToNext()) {
786 String description = c.getString(0);
787 String descriptionUpper = description.toUpperCase();
788 if (unique.containsKey(descriptionUpper))
791 storeDescription(db, descriptionsGeneration, description, descriptionUpper);
793 unique.put(descriptionUpper, true);
796 deleteNotPresentDescriptions(db, descriptionsGeneration);
798 db.setTransactionSuccessful();
804 private void storeDescription(SQLiteDatabase db, int generation, String description,
805 String descriptionUpper) {
806 db.execSQL("UPDATE description_history SET description=?, generation=? WHERE " +
807 "description_upper=?", new Object[]{description, generation, descriptionUpper
810 "INSERT INTO description_history(description, description_upper, generation) " +
811 "select ?,?,? WHERE (select changes() = 0)",
812 new Object[]{description, descriptionUpper, generation