51 lines
1.7 KiB
Dart
51 lines
1.7 KiB
Dart
import 'dart:io';
|
|
|
|
import 'package:path/path.dart' as p;
|
|
import 'package:sqflite/sqflite.dart';
|
|
|
|
/// Helper that encapsulates direct SQLite file access so UI layers remain decoupled
|
|
/// from sqflite APIs. Use this when exporting or backing up the on-device DB file.
|
|
class DatabaseMaintenanceService {
|
|
const DatabaseMaintenanceService();
|
|
|
|
/// Returns the absolute path to the primary application database file.
|
|
Future<String> databasePath() async {
|
|
final dbDir = await getDatabasesPath();
|
|
return p.join(dbDir, 'gemi_invoice.db');
|
|
}
|
|
|
|
/// Returns the database file if it currently exists on disk.
|
|
Future<File?> getDatabaseFile() async {
|
|
final path = await databasePath();
|
|
final file = File(path);
|
|
if (await file.exists()) {
|
|
return file;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// Ensures the database directory exists (useful before copying / restoring).
|
|
Future<Directory> ensureDatabaseDirectory() async {
|
|
final dbDir = await getDatabasesPath();
|
|
final dir = Directory(dbDir);
|
|
if (!await dir.exists()) {
|
|
await dir.create(recursive: true);
|
|
}
|
|
return dir;
|
|
}
|
|
|
|
/// Copies the current database file to the provided destination path.
|
|
Future<File?> copyDatabaseTo(String destinationPath) async {
|
|
final file = await getDatabaseFile();
|
|
if (file == null) return null;
|
|
final destFile = await File(destinationPath).create(recursive: true);
|
|
return file.copy(destFile.path);
|
|
}
|
|
|
|
/// Replaces the current database file with the provided source file.
|
|
Future<void> replaceDatabaseWith(File source) async {
|
|
final dir = await ensureDatabaseDirectory();
|
|
final destPath = p.join(dir.path, 'gemi_invoice.db');
|
|
await source.copy(destPath);
|
|
}
|
|
}
|