diff options
Diffstat (limited to 'lib/db.dart')
| -rw-r--r-- | lib/db.dart | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/lib/db.dart b/lib/db.dart new file mode 100644 index 0000000..8afd3eb --- /dev/null +++ b/lib/db.dart @@ -0,0 +1,55 @@ +import 'dart:io'; +import 'dart:async'; + +import 'package:path_provider/path_provider.dart'; +import 'package:sqlite3/sqlite3.dart'; +import 'package:path/path.dart' as p; + +class DB { + final Completer<Database?> _dbCompleter = Completer<Database?>(); + + Future<void> connect() async { + String path = await _getDbPath(); + Database candidate = sqlite3.open(path); + + int? userVersion = _getUserVersion(candidate); + if (userVersion == null || userVersion != 0) { + _dbCompleter.complete(null); + return; + } + + _dbCompleter.complete(candidate); + } + + void dispose() async { + if (_dbCompleter.isCompleted == false) { + return; + } + Database? db = await _dbCompleter.future; + if (db == null) return; + db.close(); + } + + static Future<String> _getDbPath() async { + Directory supportDir = await getApplicationSupportDirectory(); + return p.join(supportDir.path, 'main.sqlite3'); + } + + static int? _getUserVersion(Database db) { + ResultSet result = db.select('PRAGMA user_version;'); + if (result.length != 1) return null; + return result.first.values.first as int; + } + + Future<String?> getServerFqdn() async { + Database? db = await _dbCompleter.future; + if (db == null) return null; + + ResultSet result = db.select( + 'SELECT value FROM key_value WHERE key = \'server_fqdn\';' + ); + if (result.length != 1) return null; + + return result[0]['value']; + } +} |
