|
@@ -0,0 +1,56 @@
|
|
|
|
|
+
|
|
|
|
|
+import 'package:sembast/sembast_io.dart';
|
|
|
|
|
+import 'dart:async';
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+abstract class SemDbMgrBase<T> {
|
|
|
|
|
+
|
|
|
|
|
+ final Database database;
|
|
|
|
|
+ abstract final String repositoryName;
|
|
|
|
|
+
|
|
|
|
|
+ SemDbMgrBase(this.database);
|
|
|
|
|
+
|
|
|
|
|
+ // 获取存储
|
|
|
|
|
+ StoreRef<String, Map<String, dynamic>> get storeRef {
|
|
|
|
|
+ return StoreRef<String, Map<String, dynamic>>(repositoryName);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 转换对象为Map
|
|
|
|
|
+ Map<String, dynamic> toMap(T item);
|
|
|
|
|
+
|
|
|
|
|
+ // 从Map创建对象
|
|
|
|
|
+ T fromMap(Map<String, dynamic> map);
|
|
|
|
|
+
|
|
|
|
|
+ // 添加或更新记录
|
|
|
|
|
+ Future<String> addOrUpdate(T item, {String? id}) async {
|
|
|
|
|
+ final itemMap = toMap(item);
|
|
|
|
|
+ final recordId = id ?? DateTime.now().millisecondsSinceEpoch.toString();
|
|
|
|
|
+
|
|
|
|
|
+ await storeRef.record(recordId).put(database, itemMap);
|
|
|
|
|
+ return recordId;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 获取所有记录
|
|
|
|
|
+ Future<List<T>> getAll() async {
|
|
|
|
|
+ final records = await storeRef.find(database);
|
|
|
|
|
+ return records.map((record) => fromMap(record.value)).toList();
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 根据ID获取记录
|
|
|
|
|
+ Future<T?> getById(String id) async {
|
|
|
|
|
+ final record = await storeRef.record(id).get(database);
|
|
|
|
|
+ return record != null ? fromMap(record) : null;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 删除记录
|
|
|
|
|
+ Future<void> delete(String id) async {
|
|
|
|
|
+ await storeRef.record(id).delete(database);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 清空存储
|
|
|
|
|
+ Future<void> clear() async {
|
|
|
|
|
+ await storeRef.delete(database);
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+
|