-
Notifications
You must be signed in to change notification settings - Fork 360
Expand file tree
/
Copy pathsqlite.dart
More file actions
245 lines (225 loc) · 7.15 KB
/
sqlite.dart
File metadata and controls
245 lines (225 loc) · 7.15 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import 'dart:io';
import 'package:cw_core/db/sqlite_debug.dart';
import 'package:cw_core/root_dir.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:path/path.dart' as p;
Database? db;
Future<void> _addColumnIfNotExists(
Database db, {
required String table,
required String column,
required String definition,
}) async {
final result = await db.rawQuery("PRAGMA table_info($table)");
final columnExists = result.any((row) => row['name'] == column);
if (!columnExists) {
await db.execute(
'ALTER TABLE $table ADD COLUMN $column $definition;',
);
}
}
Future<File> sqliteDebugMarkerFile() async {
final appDir = await getAppDir();
final dbDebugMarker = p.join(appDir.path, ".sqlite_db_debug");
return File(dbDebugMarker);
}
Future<void> initDb({String? pathOverride}) async {
final dbDebugMarker = await sqliteDebugMarkerFile();
try {
if (dbDebugMarker.existsSync()) {
throw Exception("Debug marker is present");
}
await _initDb(pathOverride: pathOverride);
} catch (e, s) {
await handleSqliteError(e, s);
}
}
Future<void> _initDb({String? pathOverride}) async {
if (Platform.isLinux || Platform.isWindows) {
databaseFactory = databaseFactoryFfi;
}
// getAppDir is predictable on all platforms and ensures the db gets included in backups.
final dbFileOld = File("${await getDatabasesPath()}/cake.db");
final dbFile = File("${(await getAppDir()).path}/cake.db");
if (Platform.isAndroid && dbFileOld.existsSync() && dbFileOld.path != dbFile.path) {
final copied = dbFileOld.copySync(dbFile.path);
if (copied.existsSync()) {
dbFileOld.deleteSync();
}
}
await db?.close();
db = await openDatabase(dbFile.path, version: 4,
onUpgrade: (Database db, int oldVersion, int newVersion) async {
printV("migrating: $oldVersion, $newVersion");
if (oldVersion <= 1) {
await db.execute('''
DELETE FROM WalletInfo
WHERE walletInfoId NOT IN (
SELECT MIN(walletInfoId)
FROM WalletInfo
GROUP BY id
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_walletinfo_id_unique
ON WalletInfo (id);
''');
}
if (oldVersion <= 2) {
await db.execute('''
CREATE TABLE IF NOT EXISTS BalanceCardStyleSettings (
walletInfoId INTEGER,
accountIndex INTEGER DEFAULT -1,
gradientIndex INTEGER DEFAULT -1,
useSpecialDesign BOOLEAN DEFAULT FALSE,
backgroundImagePath TEXT DEFAULT "",
PRIMARY KEY (walletInfoId, accountIndex),
FOREIGN KEY (walletInfoId) REFERENCES WalletInfo(walletInfoId)
);
''');
await _addColumnIfNotExists(
db,
table: 'WalletInfo',
column: 'receiveInfoboxDismissed',
definition: 'BOOLEAN DEFAULT FALSE',
);
await _addColumnIfNotExists(
db,
table: 'BalanceCardStyleSettings',
column: 'cardOrder',
definition: 'INTEGER DEFAULT 0',
);
}
if (oldVersion <= 3) {
await _addColumnIfNotExists(db, table: "WalletInfo", column: "showCombinedBalance", definition: "BOOLEAN DEFAULT TRUE");
// null - primary token (eth, sol etc)
// not null - address of fav token
// if address doesn't correspond to a valid token, fallback to primary token
await _addColumnIfNotExists(db, table: "WalletInfo", column: "favoriteTokenAddress", definition: "TEXT DEFAULT NULL");
}
},
onCreate: (Database db, int version) async {
await db.execute(
'''
CREATE TABLE WalletInfo (
walletInfoId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
id TEXT NOT NULL,
name TEXT NOT NULL,
"type" INTEGER NOT NULL,
isRecovery INTEGER DEFAULT (0) NOT NULL,
walletInfoDerivationInfoId INTEGER NOT NULL,
restoreHeight INTEGER DEFAULT (0) NOT NULL,
"timestamp" INTEGER DEFAULT (0) NOT NULL,
dirPath TEXT NOT NULL,
"path" TEXT NOT NULL,
address TEXT NOT NULL,
yatEid TEXT,
yatLastUsedAddressRaw TEXT,
showIntroCakePayCard INTEGER DEFAULT (1),
addressPageType TEXT,
network TEXT,
hardwareWalletType INTEGER,
parentAddress TEXT,
hashedWalletIdentifier TEXT,
isNonSeedWallet INTEGER DEFAULT (0) NOT NULL,
sortOrder INTEGER DEFAULT (0) NOT NULL,
receiveInfoboxDismissed BOOLEAN DEFAULT FALSE,
showCombinedBalance BOOLEAN DEFAULT TRUE,
favoriteTokenAddress TEXT DEFAULT NULL
);
''');
await db.execute(
'''
CREATE TABLE WalletInfoDerivationInfo (
walletInfoDerivationInfoId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
address TEXT NOT NULL,
balance TEXT NOT NULL,
transactionsCount INTEGER DEFAULT (0) NOT NULL,
derivationType INTEGER NOT NULL,
derivationPath TEXT,
scriptType TEXT,
description TEXT
);
''');
await db.execute(
'''
CREATE TABLE WalletInfoAddress (
walletInfoAddressId INTEGER PRIMARY KEY AUTOINCREMENT,
walletInfoId INTEGER,
"type" INTEGER NOT NULL,
address TEXT NOT NULL,
CONSTRAINT WalletInfoAddress_WalletInfo_FK FOREIGN KEY (walletInfoId) REFERENCES WalletInfo(walletInfoId)
);
''');
await db.execute(
'''
CREATE TABLE WalletInfoAddressInfo (
walletInfoAddressInfoId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
walletInfoId INTEGER NOT NULL,
mapKey INTEGER NOT NULL,
mapValueAccountIndex INTEGER NOT NULL,
mapValueAddress TEXT NOT NULL,
mapValueLabel TEXT NOT NULL,
CONSTRAINT WalletInfoAddressInfo_WalletInfo_FK FOREIGN KEY (walletInfoId) REFERENCES WalletInfo(walletInfoId)
);
''');
await db.execute(
'''
CREATE TABLE "WalletInfoAddressMap" (
walletInfoAddressMapId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
walletInfoId INTEGER NOT NULL,
addressKey TEXT NOT NULL,
addressValue TEXT NOT NULL,
CONSTRAINT WalletInfoAddress_WalletInfo_FK FOREIGN KEY (walletInfoId) REFERENCES WalletInfo(walletInfoId)
);
'''
);
await db.execute('''
CREATE UNIQUE INDEX IF NOT EXISTS idx_walletinfo_id_unique
ON WalletInfo (id);
''');
await db.execute('''
CREATE TABLE BalanceCardStyleSettings (
walletInfoId INTEGER,
accountIndex INTEGER DEFAULT -1,
gradientIndex INTEGER DEFAULT -1,
useSpecialDesign BOOLEAN DEFAULT FALSE,
backgroundImagePath TEXT DEFAULT "",
cardOrder INTEGER DEFAULT 0,
PRIMARY KEY (walletInfoId, accountIndex),
FOREIGN KEY (walletInfoId) REFERENCES WalletInfo(walletInfoId)
);
''');
}
);
}
Future<Map<String, dynamic>> dumpDb() async {
try {
return await _dumpDb();
} catch (e) {
return {
"error": e.toString(),
"stackTrace": StackTrace.current.toString(),
};
}
}
Future<List<String>> _getTableNames(Database db) async {
final tableNames = await db.rawQuery('SELECT name FROM sqlite_master WHERE type = "table"');
return tableNames.map((e) => (e["name"]).toString()).toList();
}
Future<Map<String, dynamic>> _dumpDb() async {
final tableNames = await _getTableNames(db!);
final ret = <String, dynamic>{};
for (final tableName in tableNames) {
ret[tableName] = await db!.query(tableName);
}
return ret;
}
Future<Map<String, dynamic>> dumpCustomDb(String path) async {
final db = await openDatabase(path);
final tableNames = await _getTableNames(db);
final ret = <String, dynamic>{};
for (final tableName in tableNames) {
ret[tableName] = await db.query(tableName);
}
return ret;
}