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 String uuid;
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(String uuid) {
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(@Nullable String currentProfileUUID) {
101 MobileLedgerProfile result = null;
102 ArrayList<MobileLedgerProfile> list = new ArrayList<>();
103 SQLiteDatabase db = App.getDatabase();
104 try (Cursor cursor = db.rawQuery("SELECT uuid, 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.getString(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);
145 .equals(currentProfileUUID))
149 Data.profiles.postValue(list);
152 public static void storeProfilesOrder() {
153 SQLiteDatabase db = App.getDatabase();
154 db.beginTransactionNonExclusive();
157 for (MobileLedgerProfile p : Objects.requireNonNull(Data.profiles.getValue())) {
158 db.execSQL("update profiles set order_no=? where uuid=?",
159 new Object[]{orderNo, p.getUuid()});
163 db.setTransactionSuccessful();
169 static public void startEditProfileActivity(Context context, MobileLedgerProfile profile) {
170 Intent intent = new Intent(context, ProfileDetailActivity.class);
171 Bundle args = new Bundle();
172 if (profile != null) {
173 int index = Data.getProfileIndex(profile);
175 intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
177 intent.putExtras(args);
178 context.startActivity(intent, args);
180 public HledgerVersion getDetectedVersion() {
181 return detectedVersion;
183 public void setDetectedVersion(HledgerVersion detectedVersion) {
184 this.detectedVersion = detectedVersion;
186 @Contract(value = "null -> false", pure = true)
188 public boolean equals(@Nullable Object obj) {
193 if (obj.getClass() != this.getClass())
196 MobileLedgerProfile p = (MobileLedgerProfile) obj;
197 if (!uuid.equals(p.uuid))
199 if (!name.equals(p.name))
201 if (permitPosting != p.permitPosting)
203 if (showCommentsByDefault != p.showCommentsByDefault)
205 if (showCommodityByDefault != p.showCommodityByDefault)
207 if (!Objects.equals(defaultCommodity, p.defaultCommodity))
209 if (!Objects.equals(preferredAccountsFilter, p.preferredAccountsFilter))
211 if (!Objects.equals(url, p.url))
213 if (authEnabled != p.authEnabled)
215 if (!Objects.equals(authUserName, p.authUserName))
217 if (!Objects.equals(authPassword, p.authPassword))
219 if (themeHue != p.themeHue)
221 if (apiVersion != p.apiVersion)
223 if (!Objects.equals(detectedVersion, p.detectedVersion))
225 return futureDates == p.futureDates;
227 public boolean getShowCommentsByDefault() {
228 return showCommentsByDefault;
230 public void setShowCommentsByDefault(boolean newValue) {
231 this.showCommentsByDefault = newValue;
233 public boolean getShowCommodityByDefault() {
234 return showCommodityByDefault;
236 public void setShowCommodityByDefault(boolean showCommodityByDefault) {
237 this.showCommodityByDefault = showCommodityByDefault;
239 public String getDefaultCommodity() {
240 return defaultCommodity;
242 public void setDefaultCommodity(String defaultCommodity) {
243 this.defaultCommodity = defaultCommodity;
245 public void setDefaultCommodity(CharSequence defaultCommodity) {
246 if (defaultCommodity == null)
247 this.defaultCommodity = null;
249 this.defaultCommodity = String.valueOf(defaultCommodity);
251 public API getApiVersion() {
254 public void setApiVersion(API apiVersion) {
255 this.apiVersion = apiVersion;
257 public void setApiVersion(int apiVersion) {
258 this.apiVersion = API.valueOf(apiVersion);
260 public FutureDates getFutureDates() {
263 public void setFutureDates(int anInt) {
264 futureDates = FutureDates.valueOf(anInt);
266 public void setFutureDates(FutureDates futureDates) {
267 this.futureDates = futureDates;
269 public String getPreferredAccountsFilter() {
270 return preferredAccountsFilter;
272 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
273 this.preferredAccountsFilter = preferredAccountsFilter;
275 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
276 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
278 public boolean isPostingPermitted() {
279 return permitPosting;
281 public void setPostingPermitted(boolean permitPosting) {
282 this.permitPosting = permitPosting;
284 public String getUuid() {
287 public String getName() {
290 public void setName(CharSequence text) {
291 setName(String.valueOf(text));
293 public void setName(String name) {
296 public String getUrl() {
299 public void setUrl(CharSequence text) {
300 setUrl(String.valueOf(text));
302 public void setUrl(String url) {
305 public boolean isAuthEnabled() {
308 public void setAuthEnabled(boolean authEnabled) {
309 this.authEnabled = authEnabled;
311 public String getAuthUserName() {
314 public void setAuthUserName(CharSequence text) {
315 setAuthUserName(String.valueOf(text));
317 public void setAuthUserName(String authUserName) {
318 this.authUserName = authUserName;
320 public String getAuthPassword() {
323 public void setAuthPassword(CharSequence text) {
324 setAuthPassword(String.valueOf(text));
326 public void setAuthPassword(String authPassword) {
327 this.authPassword = authPassword;
329 public void storeInDB() {
330 SQLiteDatabase db = App.getDatabase();
331 db.beginTransactionNonExclusive();
333 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
334 // "url=%s, permit_posting=%s, authEnabled=%s, " +
335 // "themeHue=%d", uuid, name, url,
336 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeHue));
337 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
338 "use_authentication, auth_user, auth_password, theme, order_no, " +
339 "preferred_accounts_filter, future_dates, api_version, " +
340 "show_commodity_by_default, default_commodity, show_comments_by_default," +
341 "detected_version_pre_1_19, detected_version_major, " +
342 "detected_version_minor) " +
343 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
344 new Object[]{uuid, name, permitPosting, url, authEnabled,
345 authEnabled ? authUserName : null,
346 authEnabled ? authPassword : null, themeHue, orderNo,
347 preferredAccountsFilter, futureDates.toInt(), apiVersion.toInt(),
348 showCommodityByDefault, defaultCommodity, showCommentsByDefault,
349 (detectedVersion != null) && detectedVersion.isPre_1_20_1(),
350 (detectedVersion == null) ? 0 : detectedVersion.getMajor(),
351 (detectedVersion == null) ? 0 : detectedVersion.getMinor()
353 db.setTransactionSuccessful();
359 public void storeAccount(SQLiteDatabase db, int generation, LedgerAccount acc,
360 boolean storeUiFields) {
361 // replace into is a bad idea because it would reset hidden to its default value
362 // we like the default, but for new accounts only
363 String sql = "update accounts set generation = ?";
364 List<Object> params = new ArrayList<>();
365 params.add(generation);
367 sql += ", expanded=?";
368 params.add(acc.isExpanded() ? 1 : 0);
370 sql += " where profile=? and name=?";
372 params.add(acc.getName());
373 db.execSQL(sql, params.toArray());
375 db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level, " +
376 "expanded, generation) select ?,?,?,?,?,0,? where (select changes() = 0)",
377 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
378 acc.getLevel(), generation
380 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
382 public void storeAccountValue(SQLiteDatabase db, int generation, String name, String currency,
384 if (!TextUtils.isEmpty(currency)) {
386 try (Cursor c = db.rawQuery("select 1 from currencies where name=?",
387 new String[]{currency}))
389 exists = c.moveToFirst();
393 "insert into currencies(id, name, position, has_gap) values((select max" +
394 "(id) from currencies)+1, ?, ?, ?)", new Object[]{currency,
395 Objects.requireNonNull(
396 Data.currencySymbolPosition.getValue()).toString(),
397 Data.currencyGap.getValue()
402 db.execSQL("replace into account_values(profile, account, " +
403 "currency, value, generation) values(?, ?, ?, ?, ?);",
404 new Object[]{uuid, name, Misc.emptyIsNull(currency), amount, generation});
406 public void storeTransaction(SQLiteDatabase db, int generation, LedgerTransaction tr) {
408 // Logger.debug("storeTransaction", String.format(Locale.US, "ID %d", tr.getId()));
409 SimpleDate d = tr.getDate();
410 db.execSQL("UPDATE transactions SET year=?, month=?, day=?, description=?, comment=?, " +
411 "data_hash=?, generation=? WHERE profile=? AND id=?",
412 new Object[]{d.year, d.month, d.day, tr.getDescription(), tr.getComment(),
413 tr.getDataHash(), generation, uuid, tr.getId()
415 db.execSQL("INSERT INTO transactions(profile, id, year, month, day, description, " +
416 "comment, data_hash, generation) " +
417 "select ?,?,?,?,?,?,?,?,? WHERE (select changes() = 0)",
418 new Object[]{uuid, tr.getId(), tr.getDate().year, tr.getDate().month,
419 tr.getDate().day, tr.getDescription(), tr.getComment(),
420 tr.getDataHash(), generation
423 int accountOrderNo = 1;
424 for (LedgerTransactionAccount item : tr.getAccounts()) {
425 db.execSQL("UPDATE transaction_accounts SET account_name=?, amount=?, currency=?, " +
426 "comment=?, generation=? " +
427 "WHERE profile=? AND transaction_id=? AND order_no=?",
428 new Object[]{item.getAccountName(), item.getAmount(),
429 Misc.nullIsEmpty(item.getCurrency()), item.getComment(),
430 generation, uuid, tr.getId(), accountOrderNo
432 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
433 "order_no, account_name, amount, currency, comment, generation) " +
434 "select ?, ?, ?, ?, ?, ?, ?, ? WHERE (select changes() = 0)",
435 new Object[]{uuid, tr.getId(), accountOrderNo, item.getAccountName(),
436 item.getAmount(), Misc.nullIsEmpty(item.getCurrency()),
437 item.getComment(), generation
442 // debug("profile", String.format("Transaction %d stored", tr.getId()));
444 public String getOption(String name, String default_value) {
445 SQLiteDatabase db = App.getDatabase();
446 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
447 new String[]{uuid, name}))
449 if (cursor.moveToFirst()) {
450 String result = cursor.getString(0);
452 if (result == null) {
453 debug("profile", "returning default value for " + name);
454 result = default_value;
457 debug("profile", String.format("option %s=%s", name, result));
462 return default_value;
464 catch (Exception e) {
465 debug("db", "returning default value for " + name, e);
466 return default_value;
469 public long getLongOption(String name, long default_value) {
471 String result = getOption(name, "");
472 if ((result == null) || result.isEmpty()) {
473 debug("profile", String.format("Returning default value for option %s", name));
474 longResult = default_value;
478 longResult = Long.parseLong(result);
479 debug("profile", String.format("option %s=%s", name, result));
481 catch (Exception e) {
482 debug("profile", String.format("Returning default value for option %s", name), e);
483 longResult = default_value;
489 public void setOption(String name, String value) {
490 debug("profile", String.format("setting option %s=%s", name, value));
491 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
492 new String[]{uuid, name, value});
494 public void setLongOption(String name, long value) {
495 setOption(name, String.valueOf(value));
497 public void removeFromDB() {
498 SQLiteDatabase db = App.getDatabase();
499 debug("db", String.format("removing profile %s from DB", uuid));
500 db.beginTransactionNonExclusive();
502 Object[] uuid_param = new Object[]{uuid};
503 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
504 db.execSQL("delete from transactions where profile=?", uuid_param);
505 db.execSQL("delete from account_values where profile=?", uuid_param);
506 db.execSQL("delete from accounts where profile=?", uuid_param);
507 db.execSQL("delete from options where profile=?", uuid_param);
508 db.execSQL("delete from profiles where uuid=?", uuid_param);
509 db.setTransactionSuccessful();
515 public LedgerTransaction loadTransaction(int transactionId) {
516 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
517 tr.loadData(App.getDatabase());
521 public int getThemeHue() {
522 // debug("profile", String.format("Profile.getThemeHue() returning %d", themeHue));
523 return this.themeHue;
525 public void setThemeHue(Object o) {
526 setThemeId(Integer.parseInt(String.valueOf(o)));
528 public void setThemeId(int themeHue) {
529 // debug("profile", String.format("Profile.setThemeHue(%d) called", themeHue));
530 this.themeHue = themeHue;
532 public int getNextTransactionsGeneration(SQLiteDatabase db) {
534 try (Cursor c = db.rawQuery("SELECT generation FROM transactions WHERE profile=? LIMIT 1",
537 if (c.moveToFirst()) {
538 generation = c.getInt(0) + 1;
543 private int getNextAccountsGeneration(SQLiteDatabase db) {
545 try (Cursor c = db.rawQuery("SELECT generation FROM accounts WHERE profile=? LIMIT 1",
548 if (c.moveToFirst()) {
549 generation = c.getInt(0) + 1;
554 private void deleteNotPresentAccounts(SQLiteDatabase db, int generation) {
555 Logger.debug("db/benchmark", "Deleting obsolete accounts");
556 db.execSQL("DELETE FROM account_values WHERE profile=? AND generation <> ?",
557 new Object[]{uuid, generation});
558 db.execSQL("DELETE FROM accounts WHERE profile=? AND generation <> ?",
559 new Object[]{uuid, generation});
560 Logger.debug("db/benchmark", "Done deleting obsolete accounts");
562 private void deleteNotPresentTransactions(SQLiteDatabase db, int generation) {
563 Logger.debug("db/benchmark", "Deleting obsolete transactions");
564 db.execSQL("DELETE FROM transaction_accounts WHERE profile=? AND generation <> ?",
565 new Object[]{uuid, generation});
566 db.execSQL("DELETE FROM transactions WHERE profile=? AND generation <> ?",
567 new Object[]{uuid, generation});
568 Logger.debug("db/benchmark", "Done deleting obsolete transactions");
570 public void wipeAllData() {
571 SQLiteDatabase db = App.getDatabase();
572 db.beginTransaction();
574 String[] pUuid = new String[]{uuid};
575 db.execSQL("delete from options where profile=?", pUuid);
576 db.execSQL("delete from accounts where profile=?", pUuid);
577 db.execSQL("delete from account_values where profile=?", pUuid);
578 db.execSQL("delete from transactions where profile=?", pUuid);
579 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
580 db.setTransactionSuccessful();
581 debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));
587 public List<Currency> getCurrencies() {
588 SQLiteDatabase db = App.getDatabase();
590 ArrayList<Currency> result = new ArrayList<>();
592 try (Cursor c = db.rawQuery("SELECT c.id, c.name, c.position, c.has_gap FROM currencies c",
595 while (c.moveToNext()) {
596 Currency currency = new Currency(c.getInt(0), c.getString(1),
597 Currency.Position.valueOf(c.getString(2)), c.getInt(3) == 1);
598 result.add(currency);
604 Currency loadCurrencyByName(String name) {
605 SQLiteDatabase db = App.getDatabase();
606 Currency result = tryLoadCurrencyByName(db, name);
608 throw new RuntimeException(String.format("Unable to load currency '%s'", name));
611 private Currency tryLoadCurrencyByName(SQLiteDatabase db, String name) {
612 try (Cursor cursor = db.rawQuery(
613 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.name=?",
616 if (cursor.moveToFirst()) {
617 return new Currency(cursor.getInt(0), cursor.getString(1),
618 Currency.Position.valueOf(cursor.getString(2)), cursor.getInt(3) == 1);
623 public void storeAccountAndTransactionListAsync(List<LedgerAccount> accounts,
624 List<LedgerTransaction> transactions) {
625 if (accountAndTransactionListSaver != null)
626 accountAndTransactionListSaver.interrupt();
628 accountAndTransactionListSaver =
629 new AccountAndTransactionListSaver(this, accounts, transactions);
630 accountAndTransactionListSaver.start();
632 private Currency tryLoadCurrencyById(SQLiteDatabase db, int id) {
633 try (Cursor cursor = db.rawQuery(
634 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.id=?",
635 new String[]{String.valueOf(id)}))
637 if (cursor.moveToFirst()) {
638 return new Currency(cursor.getInt(0), cursor.getString(1),
639 Currency.Position.valueOf(cursor.getString(2)), cursor.getInt(3) == 1);
644 public Currency loadCurrencyById(int id) {
645 SQLiteDatabase db = App.getDatabase();
646 Currency result = tryLoadCurrencyById(db, id);
648 throw new RuntimeException(String.format("Unable to load currency with id '%d'", id));
652 public enum FutureDates {
653 None(0), OneWeek(7), TwoWeeks(14), OneMonth(30), TwoMonths(60), ThreeMonths(90),
654 SixMonths(180), OneYear(365), All(-1);
655 private static final SparseArray<FutureDates> map = new SparseArray<>();
658 for (FutureDates item : FutureDates.values()) {
659 map.put(item.value, item);
663 private final int value;
664 FutureDates(int value) {
667 public static FutureDates valueOf(int i) {
668 return map.get(i, None);
673 public String getText(Resources resources) {
676 return resources.getString(R.string.future_dates_7);
678 return resources.getString(R.string.future_dates_14);
680 return resources.getString(R.string.future_dates_30);
682 return resources.getString(R.string.future_dates_60);
684 return resources.getString(R.string.future_dates_90);
686 return resources.getString(R.string.future_dates_180);
688 return resources.getString(R.string.future_dates_365);
690 return resources.getString(R.string.future_dates_all);
692 return resources.getString(R.string.future_dates_none);
697 private static class AccountAndTransactionListSaver extends Thread {
698 private final MobileLedgerProfile profile;
699 private final List<LedgerAccount> accounts;
700 private final List<LedgerTransaction> transactions;
701 AccountAndTransactionListSaver(MobileLedgerProfile profile, List<LedgerAccount> accounts,
702 List<LedgerTransaction> transactions) {
703 this.accounts = accounts;
704 this.transactions = transactions;
705 this.profile = profile;
707 public int getNextDescriptionsGeneration(SQLiteDatabase db) {
709 try (Cursor c = db.rawQuery("SELECT generation FROM description_history LIMIT 1",
712 if (c.moveToFirst()) {
713 generation = c.getInt(0) + 1;
718 void deleteNotPresentDescriptions(SQLiteDatabase db, int generation) {
719 Logger.debug("db/benchmark", "Deleting obsolete descriptions");
720 db.execSQL("DELETE FROM description_history WHERE generation <> ?",
721 new Object[]{generation});
722 db.execSQL("DELETE FROM description_history WHERE generation <> ?",
723 new Object[]{generation});
724 Logger.debug("db/benchmark", "Done deleting obsolete descriptions");
728 SQLiteDatabase db = App.getDatabase();
729 db.beginTransactionNonExclusive();
731 int accountsGeneration = profile.getNextAccountsGeneration(db);
735 int transactionsGeneration = profile.getNextTransactionsGeneration(db);
739 for (LedgerAccount acc : accounts) {
740 profile.storeAccount(db, accountsGeneration, acc, false);
743 for (LedgerAmount amt : acc.getAmounts()) {
744 profile.storeAccountValue(db, accountsGeneration, acc.getName(),
745 amt.getCurrency(), amt.getAmount());
751 for (LedgerTransaction tr : transactions) {
752 profile.storeTransaction(db, transactionsGeneration, tr);
757 profile.deleteNotPresentTransactions(db, transactionsGeneration);
758 if (isInterrupted()) {
761 profile.deleteNotPresentAccounts(db, accountsGeneration);
765 Map<String, Boolean> unique = new HashMap<>();
767 debug("descriptions", "Starting refresh");
768 int descriptionsGeneration = getNextDescriptionsGeneration(db);
769 try (Cursor c = db.rawQuery("SELECT distinct description from transactions",
772 while (c.moveToNext()) {
773 String description = c.getString(0);
774 String descriptionUpper = description.toUpperCase();
775 if (unique.containsKey(descriptionUpper))
778 storeDescription(db, descriptionsGeneration, description, descriptionUpper);
780 unique.put(descriptionUpper, true);
783 deleteNotPresentDescriptions(db, descriptionsGeneration);
785 db.setTransactionSuccessful();
791 private void storeDescription(SQLiteDatabase db, int generation, String description,
792 String descriptionUpper) {
793 db.execSQL("UPDATE description_history SET description=?, generation=? WHERE " +
794 "description_upper=?", new Object[]{description, generation, descriptionUpper
797 "INSERT INTO description_history(description, description_upper, generation) " +
798 "select ?,?,? WHERE (select changes() = 0)",
799 new Object[]{description, descriptionUpper, generation