Skip to content

Commit

Permalink
Refactor DatabaseConnection
Browse files Browse the repository at this point in the history
  • Loading branch information
brminnick committed Mar 17, 2022
1 parent c109e54 commit 9540c17
Showing 1 changed file with 9 additions and 9 deletions.
18 changes: 9 additions & 9 deletions GitTrends/Database/BaseDatabase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,20 @@ namespace GitTrends
{
public abstract class BaseDatabase
{
readonly SQLiteAsyncConnection _databaseConnection;

protected BaseDatabase(IFileSystem fileSystem, IAnalyticsService analyticsService, TimeSpan expiresAt)
{
ExpiresAt = expiresAt;
AnalyticsService = analyticsService;

var databasePath = Path.Combine(fileSystem.AppDataDirectory, $"{nameof(GitTrends)}.db3");
DatabaseConnection = new SQLiteAsyncConnection(databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache);
_databaseConnection = new SQLiteAsyncConnection(databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache);
}

public TimeSpan ExpiresAt { get; }
protected IAnalyticsService AnalyticsService { get; }

SQLiteAsyncConnection DatabaseConnection { get; }

public abstract Task<int> DeleteAllData();

protected static Task<T> AttemptAndRetry<T>(Func<Task<T>> action, int numRetries = 12)
Expand All @@ -38,22 +38,22 @@ protected static Task<T> AttemptAndRetry<T>(Func<Task<T>> action, int numRetries

protected async ValueTask<SQLiteAsyncConnection> GetDatabaseConnection<T>()
{
if (!DatabaseConnection.TableMappings.Any(x => x.MappedType == typeof(T)))
if (!_databaseConnection.TableMappings.Any(x => x.MappedType == typeof(T)))
{
await DatabaseConnection.EnableWriteAheadLoggingAsync().ConfigureAwait(false);
await _databaseConnection.EnableWriteAheadLoggingAsync().ConfigureAwait(false);

try
{
await DatabaseConnection.CreateTablesAsync(CreateFlags.None, typeof(T)).ConfigureAwait(false);
await _databaseConnection.CreateTablesAsync(CreateFlags.None, typeof(T)).ConfigureAwait(false);
}
catch (SQLiteException e) when (e.Message.Contains("PRIMARY KEY", StringComparison.OrdinalIgnoreCase))
{
await DatabaseConnection.DropTableAsync(DatabaseConnection.TableMappings.First(x => x.MappedType == typeof(T)));
await DatabaseConnection.CreateTablesAsync(CreateFlags.None, typeof(T)).ConfigureAwait(false);
await _databaseConnection.DropTableAsync(_databaseConnection.TableMappings.First(x => x.MappedType == typeof(T)));
await _databaseConnection.CreateTablesAsync(CreateFlags.None, typeof(T)).ConfigureAwait(false);
}
}

return DatabaseConnection;
return _databaseConnection;
}
}
}

0 comments on commit 9540c17

Please sign in to comment.