db.dart 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import 'package:vital_local_database/index.dart';
  2. import 'package:vitalapp/database/db_patch/add_usercode.dart';
  3. import 'package:vitalapp/database/entities/diagnosis.dart';
  4. import 'package:vitalapp/database/entities/patient.dart';
  5. import 'repositories/interfaces/diagnosis.dart';
  6. import 'repositories/interfaces/patient.dart';
  7. import 'repositories/diagnosis.dart';
  8. import 'repositories/patient.dart';
  9. import 'package:fis_common/logger/logger.dart';
  10. /// vital 本地数据库对象
  11. final db = VitalDatabaseAccessor();
  12. /// vital本地数据库访问器
  13. class VitalDatabaseAccessor
  14. extends BaseDbAccessor<VitalDatabaseRepositoryStore> {
  15. final _store = VitalDatabaseRepositoryStore();
  16. final _connection = SqliteConnection(path: "vital.db");
  17. late IDatabase _database;
  18. @override
  19. IDatabase get database => _database;
  20. @override
  21. VitalDatabaseRepositoryStore get repositories => _store;
  22. /// 初始化
  23. Future<void> init() async {
  24. _database = await _connection.open();
  25. await checkAndUpgradeDatabaseVersion();
  26. _store.regRepository<IPatientRepository>(PatientRepository(database));
  27. _store.regRepository<IDiagnosisRepository>(DiagnosisRepository(database));
  28. }
  29. ///检查本地数据库版本,以判断是否需要升级
  30. Future<void> checkAndUpgradeDatabaseVersion() async {
  31. var originalVersion = await _database.getVersion();
  32. logger.w(
  33. "VitalDatabaseAccessor checkAndUpgradeDatabaseVersion originalVersion:$originalVersion.");
  34. if (originalVersion == 0) {
  35. await db.database.execute(PatientEntity.TABLE_CREATE_SQL);
  36. await db.database.execute(DiagnosisEntity.TABLE_CREATE_SQL);
  37. }
  38. var databasepatch = DatabasePatchAddUserCode(); //新增userCode
  39. var version = await databasepatch.performTask(originalVersion);
  40. if (version != originalVersion) {
  41. await _connection.close();
  42. _database = await _connection.open();
  43. }
  44. logger.w(
  45. "VitalDatabaseAccessor checkAndUpgradeDatabaseVersion version:$version.");
  46. }
  47. void dispose() {
  48. _connection.close();
  49. }
  50. }
  51. class VitalDatabaseRepositoryStore extends BaseDbAccessorRepositoryStore {
  52. /// 居民仓储
  53. IPatientRepository get patient => findRepository<IPatientRepository>()!;
  54. /// 检测记录仓储
  55. IDiagnosisRepository get diagnosis => findRepository<IDiagnosisRepository>()!;
  56. }