OpenMediacenterMobileFlutter/lib/db/database.dart

82 lines
2.2 KiB
Dart

import 'package:flutter/foundation.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart' as nativeffi;
import 'package:sqflite_common_ffi_web/sqflite_ffi_web.dart' as webffi;
import '../log/log.dart';
class Db {
late Database _db;
Future<void> init() async {
String dbpath = 'previews.db';
if (defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS) {
dbpath = join(await getDatabasesPath(), dbpath);
} else if(kIsWeb) {
databaseFactory = webffi.databaseFactoryFfiWeb;
} else {
// Initialize FFI
nativeffi.sqfliteFfiInit();
// Change the default factory
databaseFactory = nativeffi.databaseFactoryFfi;
}
_db = await openDatabase(
dbpath,
onCreate: (db, version) {
final batch = db.batch();
batch.execute(
'CREATE TABLE previews(id INTEGER PRIMARY KEY, thumbnail BLOB);',
);
batch.execute(
'CREATE TABLE settings(domain TEXT, token TEXT, videopath TEXT, tilewidth INTEGER);',
);
batch.insert("settings",
{"domain": "", "token": "", "videopath": "", "tilewidth": 0});
return batch.commit();
},
// Set the version. This executes the onCreate function and provides a
// path to perform database upgrades and downgrades.
version: 2,
);
}
/// delete all data but keep structure
Future<void> clear() async {
await _db.delete("previews");
// shrink the db file size
await _db.execute("VACUUM");
}
/// get db size in bytes
Future<int> getDbSize() async {
final batch = _db.batch();
batch.rawQuery("pragma page_count;");
batch.rawQuery("pragma page_size;");
final result = (await batch.commit(noResult: false));
print(result);
final int cnt =
((result[0] as List<Map<String, dynamic>>)[0]["page_count"] as int);
final int pagesize =
(result[1] as List<Map<String, dynamic>>)[0]["page_size"] as int;
return cnt * pagesize;
}
Database db() {
return _db;
}
static final Db _singleton = Db._internal();
factory Db() {
return _singleton;
}
Db._internal();
}