11using System ;
22using System . IO ;
33using System . Threading . Tasks ;
4- using SQLite ;
4+ using LiteDB ;
55
66namespace LLCOM . Services ;
77
88public class Database : IDisposable
99{
1010 private class Setting
1111 {
12- [ PrimaryKey ]
12+ public int Id { get ; set ; }
1313 public string Key { get ; set ; }
1414 public string Value { get ; set ; }
1515 }
1616
17- private readonly SQLiteAsyncConnection ? _db = null ;
17+ private readonly LiteDatabase ? _db = null ;
18+ private readonly ILiteCollection < Setting > ? _collection = null ;
1819
1920 /// <summary>
2021 /// 初始化全局设置的数据库
@@ -24,37 +25,46 @@ public Database(string dbFileName)
2425 if ( _db is not null )
2526 return ;
2627 // Initialize the global setting
27- // 指定路径的sqlite数据库
28+ // 指定路径的数据库
2829 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" ) ;
3932 }
4033
4134 private async Task _update ( string key , string value )
4235 {
43- if ( _db is null )
36+ if ( _db is null || _collection is null )
4437 throw new Exception ( "GlobalSetting not initialized" ) ;
45- await _db . InsertOrReplaceAsync ( new Setting
38+ await Task . Run ( ( ) =>
4639 {
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 ( ) ;
4954 } ) ;
5055 }
5156
5257 private async Task < string ? > _get ( string key )
5358 {
54- if ( _db is null )
59+ if ( _db is null || _collection is null )
5560 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 ;
5868 }
5969
6070 public async Task Set < T > ( string key , T value ) => await _update ( key , value ! . ToString ( ) ! ) ;
@@ -69,6 +79,6 @@ await _db.InsertOrReplaceAsync(new Setting
6979 public void Dispose ( )
7080 {
7181 if ( _db is not null )
72- Task . Run ( async ( ) => await _db . CloseAsync ( ) ) ;
82+ _db . Dispose ( ) ;
7383 }
7484}
0 commit comments