veilidchat/lib/veilid_support/table_db.dart

57 lines
1.3 KiB
Dart
Raw Normal View History

2023-07-19 00:09:57 -04:00
import 'package:veilid/veilid.dart';
2023-07-22 23:29:10 -04:00
import 'veilid_init.dart';
2023-07-19 00:09:57 -04:00
Future<T> tableScope<T>(
String name, Future<T> Function(VeilidTableDB tdb) callback,
{int columnCount = 1}) async {
2023-07-22 23:29:10 -04:00
final veilid = await eventualVeilid.future;
2023-07-26 14:20:29 -04:00
final tableDB = await veilid.openTableDB(name, columnCount);
2023-07-19 00:09:57 -04:00
try {
return await callback(tableDB);
} finally {
tableDB.close();
}
}
Future<T> transactionScope<T>(
VeilidTableDB tdb,
Future<T> Function(VeilidTableDBTransaction tdbt) callback,
) async {
2023-07-26 14:20:29 -04:00
final tdbt = tdb.transact();
2023-07-19 00:09:57 -04:00
try {
final ret = await callback(tdbt);
if (!tdbt.isDone()) {
await tdbt.commit();
}
return ret;
} finally {
if (!tdbt.isDone()) {
await tdbt.rollback();
}
}
}
2023-07-21 21:25:27 -04:00
abstract mixin class AsyncTableDBBacked<T> {
String tableName();
String tableKeyName();
2023-07-26 10:06:54 -04:00
T valueFromJson(Object? obj);
Object? valueToJson(T val);
2023-07-21 21:25:27 -04:00
/// Load things from storage
Future<T> load() async {
final obj = await tableScope(tableName(), (tdb) async {
final objJson = await tdb.loadStringJson(0, tableKeyName());
2023-07-26 10:06:54 -04:00
return valueFromJson(objJson);
2023-07-21 21:25:27 -04:00
});
return obj;
}
/// Store things to storage
2023-08-02 21:09:28 -04:00
Future<T> store(T obj) async {
2023-07-21 21:25:27 -04:00
await tableScope(tableName(), (tdb) async {
2023-07-26 10:06:54 -04:00
await tdb.storeStringJson(0, tableKeyName(), valueToJson(obj));
2023-07-21 21:25:27 -04:00
});
2023-08-02 21:09:28 -04:00
return obj;
2023-07-21 21:25:27 -04:00
}
}