1
1
using System ;
2
2
using System . IO ;
3
3
using System . Threading . Tasks ;
4
- using SQLite ;
4
+ using LiteDB ;
5
5
6
6
namespace LLCOM . Services ;
7
7
8
8
public class Database : IDisposable
9
9
{
10
10
private class Setting
11
11
{
12
- [ PrimaryKey ]
12
+ public int Id { get ; set ; }
13
13
public string Key { get ; set ; }
14
14
public string Value { get ; set ; }
15
15
}
16
16
17
- private readonly SQLiteAsyncConnection ? _db = null ;
17
+ private readonly LiteDatabase ? _db = null ;
18
+ private readonly ILiteCollection < Setting > ? _collection = null ;
18
19
19
20
/// <summary>
20
21
/// 初始化全局设置的数据库
@@ -24,37 +25,46 @@ public Database(string dbFileName)
24
25
if ( _db is not null )
25
26
return ;
26
27
// Initialize the global setting
27
- // 指定路径的sqlite数据库
28
+ // 指定路径的数据库
28
29
var dbPath = Path . Combine ( Utils . AppPath , dbFileName ) ;
29
- //检查数据库是否存在
30
- if ( ! File . Exists ( dbPath ) )
31
- {
32
- //创建数据库
33
- using var dbNew = new SQLiteConnection ( dbPath ) ;
34
- //创建表
35
- dbNew . CreateTable < Setting > ( ) ;
36
- }
37
- //创建数据库连接
38
- _db = new SQLiteAsyncConnection ( dbPath ) ;
30
+ _db = new LiteDatabase ( dbPath ) ;
31
+ _collection = _db . GetCollection < Setting > ( "settings" ) ;
39
32
}
40
33
41
34
private async Task _update ( string key , string value )
42
35
{
43
- if ( _db is null )
36
+ if ( _db is null || _collection is null )
44
37
throw new Exception ( "GlobalSetting not initialized" ) ;
45
- await _db . InsertOrReplaceAsync ( new Setting
38
+ await Task . Run ( ( ) =>
46
39
{
47
- Key = key ,
48
- Value = value
40
+ var v = _collection ? . FindOne ( x => x . Key == key ) ;
41
+ if ( v is null )
42
+ {
43
+ // Insert new setting
44
+ v = new Setting { Key = key , Value = value } ;
45
+ _collection ? . Insert ( v ) ;
46
+ }
47
+ else
48
+ {
49
+ // Update existing setting
50
+ v . Value = value ;
51
+ _collection ? . Update ( v ) ;
52
+ }
53
+ _db . Commit ( ) ;
49
54
} ) ;
50
55
}
51
56
52
57
private async Task < string ? > _get ( string key )
53
58
{
54
- if ( _db is null )
59
+ if ( _db is null || _collection is null )
55
60
throw new Exception ( "GlobalSetting not initialized" ) ;
56
- var setting = await _db . Table < Setting > ( ) . Where ( s => s . Key == key ) . FirstOrDefaultAsync ( ) ;
57
- return setting ? . Value ;
61
+ string ? value = null ;
62
+ await Task . Run ( ( ) =>
63
+ {
64
+ var v = _collection ? . FindOne ( x => x . Key == key ) ;
65
+ value = v ? . Value ;
66
+ } ) ;
67
+ return value ;
58
68
}
59
69
60
70
public async Task Set < T > ( string key , T value ) => await _update ( key , value ! . ToString ( ) ! ) ;
@@ -69,6 +79,6 @@ await _db.InsertOrReplaceAsync(new Setting
69
79
public void Dispose ( )
70
80
{
71
81
if ( _db is not null )
72
- Task . Run ( async ( ) => await _db . CloseAsync ( ) ) ;
82
+ _db . Dispose ( ) ;
73
83
}
74
84
}
0 commit comments