91 lines
2.5 KiB
C#
91 lines
2.5 KiB
C#
using System.Reactive.Linq;
|
|
using InnovEnergy.App.Backend.DataTypes;
|
|
using InnovEnergy.App.Backend.Relations;
|
|
using InnovEnergy.Lib.Utils;
|
|
using SQLite;
|
|
|
|
|
|
|
|
namespace InnovEnergy.App.Backend.Database;
|
|
|
|
|
|
public static partial class Db
|
|
{
|
|
internal const String DbPath = "./db.sqlite";
|
|
|
|
private static SQLiteConnection Connection { get; } = new SQLiteConnection(DbPath);
|
|
|
|
public static TableQuery<Session> Sessions => Connection.Table<Session>();
|
|
public static TableQuery<Folder> Folders => Connection.Table<Folder>();
|
|
public static TableQuery<Installation> Installations => Connection.Table<Installation>();
|
|
public static TableQuery<User> Users => Connection.Table<User>();
|
|
public static TableQuery<User2Folder> User2Folder => Connection.Table<User2Folder>();
|
|
public static TableQuery<User2Installation> User2Installation => Connection.Table<User2Installation>();
|
|
|
|
|
|
static Db()
|
|
{
|
|
// on startup create/migrate tables
|
|
|
|
Connection.RunInTransaction(() =>
|
|
{
|
|
Connection.CreateTable<User>();
|
|
Connection.CreateTable<Installation>();
|
|
Connection.CreateTable<Folder>();
|
|
Connection.CreateTable<User2Folder>();
|
|
Connection.CreateTable<User2Installation>();
|
|
Connection.CreateTable<Session>();
|
|
});
|
|
|
|
|
|
Observable.Interval(TimeSpan.FromDays(1))
|
|
.StartWith(0) // Do it right away (on startup)
|
|
.Subscribe(Cleanup); // and then daily
|
|
}
|
|
|
|
|
|
|
|
private static Boolean RunTransaction(Func<Boolean> func)
|
|
{
|
|
var savepoint = Connection.SaveTransactionPoint();
|
|
var success = false;
|
|
|
|
try
|
|
{
|
|
success = func();
|
|
}
|
|
finally
|
|
{
|
|
if (success)
|
|
Connection.Release(savepoint);
|
|
else
|
|
Connection.RollbackTo(savepoint);
|
|
}
|
|
|
|
return success;
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
private static void Cleanup(Int64 _)
|
|
{
|
|
DeleteS3Keys();
|
|
DeleteStaleSessions();
|
|
}
|
|
|
|
private static void DeleteStaleSessions()
|
|
{
|
|
var deadline = DateTime.Now - Session.MaxAge;
|
|
Sessions.Delete(s => s.LastSeen < deadline);
|
|
}
|
|
|
|
private static void DeleteS3Keys()
|
|
{
|
|
void DeleteKeys() => Installations.Do(i => i.S3Key = "").ForEach(Update); // TODO
|
|
|
|
Connection.RunInTransaction(DeleteKeys);
|
|
}
|
|
} |