AndroidAPS/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java

460 lines
18 KiB
Java
Raw Normal View History

2016-06-05 01:40:35 +02:00
package info.nightscout.androidaps.db;
import android.content.Context;
import android.database.DatabaseUtils;
2016-06-05 01:40:35 +02:00
import android.database.sqlite.SQLiteDatabase;
2016-06-12 14:18:21 +02:00
import android.support.annotation.Nullable;
2016-06-05 01:40:35 +02:00
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
2016-06-07 21:48:17 +02:00
import com.j256.ormlite.stmt.PreparedQuery;
2016-06-05 01:40:35 +02:00
import com.j256.ormlite.stmt.QueryBuilder;
2016-06-09 00:01:28 +02:00
import com.j256.ormlite.stmt.Where;
2016-06-05 01:40:35 +02:00
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
2016-06-07 21:48:17 +02:00
2016-06-05 01:40:35 +02:00
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
2016-07-11 18:07:54 +02:00
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
2016-07-11 18:07:54 +02:00
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
2016-06-07 21:48:17 +02:00
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
2016-06-07 21:48:17 +02:00
2016-06-05 01:40:35 +02:00
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
2016-06-07 21:48:17 +02:00
private static Logger log = LoggerFactory.getLogger(DatabaseHelper.class);
2016-06-05 01:40:35 +02:00
2016-06-07 21:48:17 +02:00
public static final String DATABASE_NAME = "AndroidAPSDb";
2016-07-21 15:10:42 +02:00
public static final String DATABASE_BGREADINGS = "BgReadings";
public static final String DATABASE_TEMPBASALS = "TempBasals";
2017-01-13 22:36:47 +01:00
public static final String DATABASE_TEMPTARGETS = "TempTargets";
2016-07-21 15:10:42 +02:00
public static final String DATABASE_TREATMENTS = "Treatments";
public static final String DATABASE_DANARHISTORY = "DanaRHistory";
2017-02-24 13:02:44 +01:00
public static final String DATABASE_DBREQUESTS = "DBRequests";
2016-06-05 01:40:35 +02:00
2017-04-21 11:45:25 +02:00
private static final int DATABASE_VERSION = 6;
2016-06-05 01:40:35 +02:00
private static Long latestTreatmentChange = null;
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledPost = null;
2016-06-07 21:48:17 +02:00
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
2017-01-14 00:37:35 +01:00
onCreate(getWritableDatabase(), getConnectionSource());
2016-06-07 21:48:17 +02:00
}
2016-06-05 01:40:35 +02:00
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
2016-06-07 21:48:17 +02:00
try {
log.info("onCreate");
TableUtils.createTableIfNotExists(connectionSource, TempBasal.class);
2017-01-13 22:36:47 +01:00
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
2016-06-07 21:48:17 +02:00
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
2016-07-21 15:10:42 +02:00
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
2017-02-24 13:02:44 +01:00
TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
2016-06-07 21:48:17 +02:00
} catch (SQLException e) {
2017-01-14 00:37:35 +01:00
log.error("Can't create database", e);
2016-06-07 21:48:17 +02:00
throw new RuntimeException(e);
}
2016-06-05 01:40:35 +02:00
}
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
2016-06-07 21:48:17 +02:00
try {
log.info(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, TempBasal.class, true);
2017-01-13 22:36:47 +01:00
TableUtils.dropTable(connectionSource, TempTarget.class, true);
2016-06-07 21:48:17 +02:00
TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
2016-07-21 15:10:42 +02:00
TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true);
2017-02-24 13:02:44 +01:00
TableUtils.dropTable(connectionSource, DbRequest.class, true);
2016-06-07 21:48:17 +02:00
onCreate(database, connectionSource);
} catch (SQLException e) {
2017-01-14 00:37:35 +01:00
log.error("Can't drop databases", e);
2016-06-07 21:48:17 +02:00
throw new RuntimeException(e);
}
2016-06-05 01:40:35 +02:00
}
/**
2016-06-07 21:48:17 +02:00
* Close the database connections and clear any cached DAOs.
*/
@Override
public void close() {
super.close();
}
public void cleanUpDatabases() {
// TODO: call it somewhere
2016-07-21 15:10:42 +02:00
log.debug("Before BgReadings size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_BGREADINGS));
2017-01-13 22:36:47 +01:00
getWritableDatabase().delete(DATABASE_BGREADINGS, "timeIndex" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
2016-07-21 15:10:42 +02:00
log.debug("After BgReadings size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_BGREADINGS));
2016-07-21 15:10:42 +02:00
log.debug("Before TempBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPBASALS));
2017-01-13 22:36:47 +01:00
getWritableDatabase().delete(DATABASE_TEMPBASALS, "timeIndex" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
2016-07-21 15:10:42 +02:00
log.debug("After TempBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPBASALS));
2017-01-13 22:36:47 +01:00
log.debug("Before TempTargets size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPTARGETS));
getWritableDatabase().delete(DATABASE_TEMPTARGETS, "timeIndex" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
log.debug("After TempTargets size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPTARGETS));
2016-07-21 15:10:42 +02:00
log.debug("Before Treatments size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TREATMENTS));
2017-01-13 22:36:47 +01:00
getWritableDatabase().delete(DATABASE_TREATMENTS, "timeIndex" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
2016-07-21 15:10:42 +02:00
log.debug("After Treatments size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TREATMENTS));
2016-07-08 00:17:02 +02:00
2017-01-13 22:36:47 +01:00
log.debug("Before History size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_DANARHISTORY));
getWritableDatabase().delete(DATABASE_DANARHISTORY, "recordDate" + " < '" + (new Date().getTime() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
log.debug("After History size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_DANARHISTORY));
}
2016-06-07 21:48:17 +02:00
public void resetDatabases() {
try {
TableUtils.dropTable(connectionSource, TempBasal.class, true);
2017-01-13 22:36:47 +01:00
TableUtils.dropTable(connectionSource, TempTarget.class, true);
2016-06-07 21:48:17 +02:00
TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
2016-07-21 15:10:42 +02:00
TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true);
2017-02-24 13:02:44 +01:00
//DbRequests can be cleared from NSClient fragment
2016-06-07 21:48:17 +02:00
TableUtils.createTableIfNotExists(connectionSource, TempBasal.class);
2017-01-13 22:36:47 +01:00
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
2016-06-07 21:48:17 +02:00
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
2016-07-21 15:10:42 +02:00
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
latestTreatmentChange = 0L;
2016-06-07 21:48:17 +02:00
} catch (SQLException e) {
e.printStackTrace();
}
}
public void resetTreatments() {
try {
TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
latestTreatmentChange = 0L;
2016-06-07 21:48:17 +02:00
} catch (SQLException e) {
e.printStackTrace();
}
}
2016-06-05 01:40:35 +02:00
public void resetTempTargets() {
try {
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
} catch (SQLException e) {
e.printStackTrace();
2016-06-07 21:48:17 +02:00
}
}
2016-06-05 01:40:35 +02:00
public Dao<TempBasal, Long> getDaoTempBasals() throws SQLException {
2016-06-07 21:48:17 +02:00
return getDao(TempBasal.class);
2016-06-05 01:40:35 +02:00
}
2017-01-13 22:36:47 +01:00
public Dao<TempTarget, Long> getDaoTempTargets() throws SQLException {
return getDao(TempTarget.class);
2016-06-05 01:40:35 +02:00
}
private Dao<Treatment, Long> getDaoTreatments() throws SQLException {
2016-06-07 21:48:17 +02:00
return getDao(Treatment.class);
}
public Dao<BgReading, Long> getDaoBgReadings() throws SQLException {
return getDao(BgReading.class);
}
2016-07-27 17:49:56 +02:00
public Dao<DanaRHistoryRecord, String> getDaoDanaRHistory() throws SQLException {
2016-07-21 15:10:42 +02:00
return getDao(DanaRHistoryRecord.class);
2016-07-08 00:17:02 +02:00
}
2017-02-24 13:02:44 +01:00
public Dao<DbRequest, String> getDaoDbRequest() throws SQLException {
return getDao(DbRequest.class);
}
public long size(String database) {
return DatabaseUtils.queryNumEntries(getReadableDatabase(), database);
}
2017-01-09 10:57:15 +01:00
public List<BgReading> getBgreadingsDataFromTime(long mills, boolean ascending) {
2016-06-09 00:01:28 +02:00
try {
Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();
List<BgReading> bgReadings;
QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
2017-01-06 22:42:37 +01:00
queryBuilder.orderBy("timeIndex", ascending);
2016-06-09 00:01:28 +02:00
Where where = queryBuilder.where();
2016-12-07 01:22:47 +01:00
where.ge("timeIndex", mills).and().gt("value", 38);
2016-06-09 00:01:28 +02:00
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings;
} catch (SQLException e) {
e.printStackTrace();
}
return new ArrayList<BgReading>();
}
2017-02-24 13:02:44 +01:00
// DbRequests handling
public void create(DbRequest dbr) {
try {
getDaoDbRequest().create(dbr);
} catch (SQLException e) {
e.printStackTrace();
}
}
public int delete(DbRequest dbr) {
2017-02-24 13:02:44 +01:00
try {
return getDaoDbRequest().delete(dbr);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
public int deleteDbRequest(String nsClientId) {
try {
return getDaoDbRequest().deleteById(nsClientId);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
public int deleteDbRequestbyMongoId(String action, String id) {
try {
QueryBuilder<DbRequest, String> queryBuilder = getDaoDbRequest().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", id).and().eq("action", action);
queryBuilder.limit(10L);
PreparedQuery<DbRequest> preparedQuery = queryBuilder.prepare();
List<DbRequest> dbList = getDaoDbRequest().query(preparedQuery);
if (dbList.size() != 1) {
log.error("deleteDbRequestbyMongoId query size: " + dbList.size());
} else {
//log.debug("Treatment findTreatmentById found: " + trList.get(0).log());
return delete(dbList.get(0));
}
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
public void deleteAllDbRequests() {
try {
TableUtils.clearTable(connectionSource, DbRequest.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
// TREATMENT HANDLING
public boolean affectingIobCob(Treatment t) {
Treatment existing = findTreatmentByTimeIndex(t.timeIndex);
if (existing == null)
return true;
if (existing.insulin == t.insulin && existing.carbs == t.carbs)
return false;
return true;
}
public int update(Treatment treatment) {
int updated = 0;
try {
boolean historyChange = affectingIobCob(treatment);
updated = getDaoTreatments().update(treatment);
if (historyChange)
latestTreatmentChange = treatment.getTimeIndex();
} catch (SQLException e) {
e.printStackTrace();
}
scheduleTreatmentChange();
return updated;
}
public Dao.CreateOrUpdateStatus createOrUpdate(Treatment treatment) {
Dao.CreateOrUpdateStatus status = null;
try {
boolean historyChange = affectingIobCob(treatment);
status = getDaoTreatments().createOrUpdate(treatment);
if (historyChange)
latestTreatmentChange = treatment.getTimeIndex();
} catch (SQLException e) {
e.printStackTrace();
}
scheduleTreatmentChange();
return status;
}
public void create(Treatment treatment) {
try {
getDaoTreatments().create(treatment);
latestTreatmentChange = treatment.getTimeIndex();
} catch (SQLException e) {
e.printStackTrace();
}
scheduleTreatmentChange();
}
2017-02-14 21:13:13 +01:00
public void delete(Treatment treatment) {
try {
getDaoTreatments().delete(treatment);
latestTreatmentChange = treatment.getTimeIndex();
} catch (SQLException e) {
e.printStackTrace();
}
scheduleTreatmentChange();
}
public int delete(String _id) {
Treatment stored = findTreatmentById(_id);
int removed = 0;
if (stored != null) {
log.debug("REMOVE: Existing treatment (removing): " + _id);
try {
removed = getDaoTreatments().delete(stored);
} catch (SQLException e) {
e.printStackTrace();
}
if (Config.logIncommingData)
log.debug("Records removed: " + removed);
latestTreatmentChange = stored.getTimeIndex();
scheduleTreatmentChange();
} else {
log.debug("REMOVE: Not stored treatment (ignoring): " + _id);
}
return removed;
}
@Nullable
public Treatment findTreatmentById(String _id) {
try {
Dao<Treatment, Long> daoTreatments = getDaoTreatments();
QueryBuilder<Treatment, Long> queryBuilder = daoTreatments.queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
queryBuilder.limit(10L);
PreparedQuery<Treatment> preparedQuery = queryBuilder.prepare();
List<Treatment> trList = daoTreatments.query(preparedQuery);
if (trList.size() != 1) {
//log.debug("Treatment findTreatmentById query size: " + trList.size());
return null;
} else {
//log.debug("Treatment findTreatmentById found: " + trList.get(0).log());
return trList.get(0);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Nullable
public Treatment findTreatmentByTimeIndex(Long timeIndex) {
try {
QueryBuilder<Treatment, String> qb = null;
Dao<Treatment, Long> daoTreatments = getDaoTreatments();
QueryBuilder<Treatment, Long> queryBuilder = daoTreatments.queryBuilder();
Where where = queryBuilder.where();
where.eq("timeIndex", timeIndex);
queryBuilder.limit(10L);
PreparedQuery<Treatment> preparedQuery = queryBuilder.prepare();
List<Treatment> trList = daoTreatments.query(preparedQuery);
if (trList.size() != 1) {
log.debug("Treatment findTreatmentByTimeIndex query size: " + trList.size());
return null;
} else {
log.debug("Treatment findTreatmentByTimeIndex found: " + trList.get(0).log());
return trList.get(0);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
static public void scheduleTreatmentChange() {
class PostRunnable implements Runnable {
public void run() {
MainApp.bus().post(new EventTreatmentChange());
if (latestTreatmentChange != null)
MainApp.bus().post(new EventNewHistoryData(latestTreatmentChange));
latestTreatmentChange = null;
scheduledPost = null;
}
}
// prepare task for execution in 5 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledPost != null)
scheduledPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 5;
scheduledPost = worker.schedule(task, sec, TimeUnit.SECONDS);
}
2017-01-09 10:57:15 +01:00
public List<Treatment> getTreatmentDataFromTime(long mills, boolean ascending) {
try {
Dao<Treatment, Long> daoTreatments = getDaoTreatments();
List<Treatment> treatments;
QueryBuilder<Treatment, Long> queryBuilder = daoTreatments.queryBuilder();
queryBuilder.orderBy("timeIndex", ascending);
Where where = queryBuilder.where();
where.ge("timeIndex", mills);
PreparedQuery<Treatment> preparedQuery = queryBuilder.prepare();
treatments = daoTreatments.query(preparedQuery);
return treatments;
} catch (SQLException e) {
e.printStackTrace();
}
return new ArrayList<Treatment>();
}
2017-01-13 23:43:17 +01:00
public List<TempTarget> getTemptargetsDataFromTime(long mills, boolean ascending) {
try {
Dao<TempTarget, Long> daoTempTargets = getDaoTempTargets();
List<TempTarget> tempTargets;
QueryBuilder<TempTarget, Long> queryBuilder = daoTempTargets.queryBuilder();
queryBuilder.orderBy("timeIndex", ascending);
Where where = queryBuilder.where();
where.ge("timeIndex", mills);
PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
tempTargets = daoTempTargets.query(preparedQuery);
return tempTargets;
} catch (SQLException e) {
e.printStackTrace();
}
return new ArrayList<TempTarget>();
}
2016-06-17 14:42:02 +02:00
2017-01-09 10:57:15 +01:00
public List<TempBasal> getTempbasalsDataFromTime(long mills, boolean ascending, boolean isExtended) {
try {
Dao<TempBasal, Long> daoTempbasals = getDaoTempBasals();
List<TempBasal> tempbasals;
QueryBuilder<TempBasal, Long> queryBuilder = daoTempbasals.queryBuilder();
queryBuilder.orderBy("timeIndex", ascending);
Where where = queryBuilder.where();
where.ge("timeIndex", mills).and().eq("isExtended", isExtended);
PreparedQuery<TempBasal> preparedQuery = queryBuilder.prepare();
tempbasals = daoTempbasals.query(preparedQuery);
return tempbasals;
} catch (SQLException e) {
e.printStackTrace();
}
return new ArrayList<TempBasal>();
}
2016-06-05 01:40:35 +02:00
}