XAML-Map-Control/Caches/SQLiteCache/SQLiteCache.cs

294 lines
9.2 KiB
C#
Raw Normal View History

2024-02-03 20:53:32 +01:00
// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
2025-01-01 18:57:55 +01:00
// Copyright © Clemens Fischer
2024-02-03 20:53:32 +01:00
// Licensed under the Microsoft Public License (Ms-PL)
using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Data.Common;
using System.Data.SQLite;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace MapControl.Caching
{
/// <summary>
2025-02-21 21:58:45 +01:00
/// IDistributedCache implementation based on System.Data.SQLite.
2024-02-03 20:53:32 +01:00
/// </summary>
2024-08-20 17:59:39 +02:00
public sealed class SQLiteCache : IDistributedCache, IDisposable
2024-02-03 20:53:32 +01:00
{
private readonly SQLiteConnection connection;
2025-02-20 20:29:49 +01:00
private readonly Timer expirationScanTimer;
2024-02-03 20:53:32 +01:00
public SQLiteCache(string path)
2025-02-19 19:34:08 +01:00
: this(path, TimeSpan.FromHours(1))
{
}
2025-02-20 20:29:49 +01:00
public SQLiteCache(string path, TimeSpan expirationScanFrequency)
2024-02-03 20:53:32 +01:00
{
if (string.IsNullOrEmpty(path))
{
2024-02-05 16:33:19 +01:00
throw new ArgumentException($"The {nameof(path)} argument must not be null or empty.", nameof(path));
2024-02-03 20:53:32 +01:00
}
if (string.IsNullOrEmpty(Path.GetExtension(path)))
{
path = Path.Combine(path, "TileCache.sqlite");
}
2024-02-03 21:12:05 +01:00
connection = new SQLiteConnection("Data Source=" + Path.GetFullPath(path));
2024-02-03 20:53:32 +01:00
connection.Open();
using (var command = new SQLiteCommand("create table if not exists items (key text primary key, expiration integer, buffer blob)", connection))
{
command.ExecuteNonQuery();
}
2024-08-31 16:39:49 +02:00
Debug.WriteLine($"{nameof(SQLiteCache)}: Opened database {path}");
2024-02-03 20:53:32 +01:00
2025-02-20 20:29:49 +01:00
if (expirationScanFrequency > TimeSpan.Zero)
2025-02-19 19:34:08 +01:00
{
2025-02-20 20:29:49 +01:00
expirationScanTimer = new Timer(_ => DeleteExpiredItems(), null, TimeSpan.Zero, expirationScanFrequency);
2025-02-19 19:34:08 +01:00
}
2024-02-03 20:53:32 +01:00
}
public void Dispose()
{
2025-02-20 20:29:49 +01:00
expirationScanTimer?.Dispose();
2024-02-03 20:53:32 +01:00
connection.Dispose();
}
public byte[] Get(string key)
{
2024-02-05 16:33:19 +01:00
CheckArgument(key);
2024-02-03 20:53:32 +01:00
byte[] value = null;
try
{
using (var command = GetItemCommand(key))
{
var reader = command.ExecuteReader();
if (reader.Read() && !ReadValue(reader, ref value))
{
Remove(key);
}
}
}
catch (Exception ex)
{
2024-08-31 16:39:49 +02:00
Debug.WriteLine($"{nameof(SQLiteCache)}.Get({key}): {ex.Message}");
2024-02-03 20:53:32 +01:00
}
return value;
}
public async Task<byte[]> GetAsync(string key, CancellationToken token = default)
{
2024-02-05 16:33:19 +01:00
CheckArgument(key);
2024-02-03 20:53:32 +01:00
byte[] value = null;
try
{
using (var command = GetItemCommand(key))
{
var reader = await command.ExecuteReaderAsync(token);
2024-02-05 16:33:19 +01:00
if (await reader.ReadAsync(token) && !ReadValue(reader, ref value))
2024-02-03 20:53:32 +01:00
{
await RemoveAsync(key);
}
}
}
catch (Exception ex)
{
2024-08-31 16:39:49 +02:00
Debug.WriteLine($"{nameof(SQLiteCache)}.GetAsync({key}): {ex.Message}");
2024-02-03 20:53:32 +01:00
}
return value;
}
public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
{
2024-02-05 16:33:19 +01:00
CheckArguments(key, value, options);
2024-02-03 20:53:32 +01:00
try
{
using (var command = SetItemCommand(key, value, options))
{
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
2024-08-31 16:39:49 +02:00
Debug.WriteLine($"{nameof(SQLiteCache)}.Set({key}): {ex.Message}");
2024-02-03 20:53:32 +01:00
}
}
public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default)
{
2024-02-05 16:33:19 +01:00
CheckArguments(key, value, options);
2024-02-03 20:53:32 +01:00
try
{
using (var command = SetItemCommand(key, value, options))
{
await command.ExecuteNonQueryAsync(token);
}
}
catch (Exception ex)
{
2024-08-31 16:39:49 +02:00
Debug.WriteLine($"{nameof(SQLiteCache)}.SetAsync({key}): {ex.Message}");
2024-02-03 20:53:32 +01:00
}
}
public void Refresh(string key)
{
}
public Task RefreshAsync(string key, CancellationToken token = default)
{
2024-02-05 16:33:19 +01:00
return Task.CompletedTask;
2024-02-03 20:53:32 +01:00
}
public void Remove(string key)
{
2024-02-05 16:33:19 +01:00
CheckArgument(key);
2024-02-03 20:53:32 +01:00
try
{
using (var command = RemoveItemCommand(key))
{
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
2024-08-31 16:39:49 +02:00
Debug.WriteLine($"{nameof(SQLiteCache)}.Remove({key}): {ex.Message}");
2024-02-03 20:53:32 +01:00
}
}
public async Task RemoveAsync(string key, CancellationToken token = default)
{
2024-02-05 16:33:19 +01:00
CheckArgument(key);
2024-02-03 20:53:32 +01:00
try
{
using (var command = RemoveItemCommand(key))
{
await command.ExecuteNonQueryAsync();
}
}
catch (Exception ex)
{
2024-08-31 16:39:49 +02:00
Debug.WriteLine($"{nameof(SQLiteCache)}.RemoveAsync({key}): {ex.Message}");
2024-02-03 20:53:32 +01:00
}
}
2025-02-20 20:29:49 +01:00
public void DeleteExpiredItems()
{
using (var command = new SQLiteCommand("delete from items where expiration < @exp", connection))
{
2025-02-20 21:37:48 +01:00
command.Parameters.AddWithValue("@exp", DateTimeOffset.UtcNow.Ticks);
command.ExecuteNonQuery();
}
#if DEBUG
using (var command = new SQLiteCommand("select changes()", connection))
{
var deleted = (long)command.ExecuteScalar();
if (deleted > 0)
{
2024-08-31 16:39:49 +02:00
Debug.WriteLine($"{nameof(SQLiteCache)}: Deleted {deleted} expired items");
}
}
#endif
}
2025-02-20 20:29:49 +01:00
public async Task DeleteExpiredItemsAsync()
{
using (var command = new SQLiteCommand("delete from items where expiration < @exp", connection))
{
2025-02-20 21:37:48 +01:00
command.Parameters.AddWithValue("@exp", DateTimeOffset.UtcNow.Ticks);
await command.ExecuteNonQueryAsync();
}
#if DEBUG
using (var command = new SQLiteCommand("select changes()", connection))
{
var deleted = (long)await command.ExecuteScalarAsync();
if (deleted > 0)
{
2024-08-31 16:39:49 +02:00
Debug.WriteLine($"{nameof(SQLiteCache)}: Deleted {deleted} expired items");
}
}
#endif
}
2024-02-03 20:53:32 +01:00
private SQLiteCommand GetItemCommand(string key)
{
var command = new SQLiteCommand("select expiration, buffer from items where key = @key", connection);
command.Parameters.AddWithValue("@key", key);
return command;
}
private SQLiteCommand RemoveItemCommand(string key)
{
var command = new SQLiteCommand("delete from items where key = @key", connection);
command.Parameters.AddWithValue("@key", key);
return command;
}
private SQLiteCommand SetItemCommand(string key, byte[] buffer, DistributedCacheEntryOptions options)
{
2025-02-20 20:29:49 +01:00
var expiration = options.AbsoluteExpiration.HasValue
? options.AbsoluteExpiration.Value
2025-02-20 21:37:48 +01:00
: DateTimeOffset.UtcNow.Add(options.AbsoluteExpirationRelativeToNow ?? (options.SlidingExpiration ?? TimeSpan.FromDays(1)));
2024-02-03 20:53:32 +01:00
var command = new SQLiteCommand("insert or replace into items (key, expiration, buffer) values (@key, @exp, @buf)", connection);
command.Parameters.AddWithValue("@key", key);
command.Parameters.AddWithValue("@exp", expiration.Ticks);
2024-02-05 16:33:19 +01:00
command.Parameters.AddWithValue("@buf", buffer);
2024-02-03 20:53:32 +01:00
return command;
}
2024-02-05 16:33:19 +01:00
private static bool ReadValue(DbDataReader reader, ref byte[] value)
2024-02-03 20:53:32 +01:00
{
var expiration = new DateTimeOffset((long)reader["expiration"], TimeSpan.Zero);
2025-02-20 21:37:48 +01:00
if (expiration <= DateTimeOffset.UtcNow)
2024-02-03 20:53:32 +01:00
{
return false;
}
value = (byte[])reader["buffer"];
return true;
}
2024-02-05 16:33:19 +01:00
private static void CheckArgument(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException($"The {nameof(key)} argument must not be null or empty.", nameof(key));
}
}
private static void CheckArguments(string key, byte[] value, DistributedCacheEntryOptions options)
{
CheckArgument(key);
if (value == null)
{
throw new ArgumentNullException($"The {nameof(value)} argument must not be null.", nameof(value));
}
if (options == null)
{
throw new ArgumentNullException($"The {nameof(options)} argument must not be null.", nameof(options));
}
}
2024-02-03 20:53:32 +01:00
}
}