summaryrefslogtreecommitdiff
path: root/lib/db.dart
blob: 8afd3ebe5716c1b353e4be49b62184307dafb8a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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'];
  }
}