|
| 1 | +namespace Simple.Sqlite; |
| 2 | + |
| 3 | +using Simple.DatabaseWrapper.Attributes; |
| 4 | +using System; |
| 5 | +using System.Linq; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// A Simple KeyValue storage |
| 9 | +/// </summary> |
| 10 | +public class KeyValueStorage |
| 11 | +{ |
| 12 | + private readonly ConnectionFactory db; |
| 13 | + |
| 14 | + /// <summary> |
| 15 | + /// Creates a new KeyValueStorage using a ConnectionFactory |
| 16 | + /// </summary> |
| 17 | + public KeyValueStorage(ConnectionFactory db) |
| 18 | + { |
| 19 | + this.db = db; |
| 20 | + |
| 21 | + using var cnn = db.GetConnection(); |
| 22 | + cnn.CreateTables() |
| 23 | + .Add<KVStorageTable>() |
| 24 | + .Commit(); |
| 25 | + } |
| 26 | + /// <summary> |
| 27 | + /// Sets a new KeyValue pair |
| 28 | + /// </summary> |
| 29 | + public void SetKey<T>(string key, T? value) |
| 30 | + { |
| 31 | + if (string.IsNullOrEmpty(key)) |
| 32 | + { |
| 33 | + throw new ArgumentException($"'{nameof(key)}' cannot be null or empty.", nameof(key)); |
| 34 | + } |
| 35 | + |
| 36 | + using var cnn = db.GetConnection(); |
| 37 | + |
| 38 | + if (value == null) |
| 39 | + { |
| 40 | + cnn.Execute($"DELETE FROM KVStorageTable WHERE {nameof(KVStorageTable.Key)} = @key", new { key }); |
| 41 | + } |
| 42 | + else |
| 43 | + { |
| 44 | + cnn.Insert(new KVStorageTable { Key = normalizeKey(key), Value = value }, OnConflict.Replace); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + /// <summary> |
| 49 | + /// Gets the Value from a Key |
| 50 | + /// Inexistent keys returns as null |
| 51 | + /// </summary> |
| 52 | + /// <returns>Key's value or NULL</returns> |
| 53 | + public T? GetKey<T>(string key) |
| 54 | + { |
| 55 | + using var cnn = db.GetConnection(); |
| 56 | + var values = cnn.Query<T>("SELECT Value FROM KVStorageTable WHERE Key = @Key", new { Key = normalizeKey(key) }) |
| 57 | + .ToArray(); |
| 58 | + |
| 59 | + if (values.Length == 0) return default; |
| 60 | + return values[0]; |
| 61 | + } |
| 62 | + |
| 63 | + private static string normalizeKey(string key) => key.Trim().ToUpper(); |
| 64 | + |
| 65 | + internal record KVStorageTable |
| 66 | + { |
| 67 | + [PrimaryKey] |
| 68 | + public string Key { get; set; } = default!; |
| 69 | + public object Value { get; set; } = default!; |
| 70 | + } |
| 71 | +} |
0 commit comments