2022-08-28 20:51:12 +00:00
|
|
|
import 'package:flutter/foundation.dart';
|
|
|
|
import 'package:path/path.dart';
|
|
|
|
import 'package:sqflite/sqflite.dart';
|
|
|
|
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
|
|
|
|
|
|
|
import '../log/log.dart';
|
|
|
|
|
|
|
|
class Db {
|
|
|
|
late Database _db;
|
|
|
|
|
|
|
|
void init() async {
|
|
|
|
if (kIsWeb) {
|
|
|
|
Log.i("Database on web is not supported");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
String dbpath = 'previews.db';
|
|
|
|
if (defaultTargetPlatform == TargetPlatform.android ||
|
|
|
|
defaultTargetPlatform == TargetPlatform.iOS) {
|
|
|
|
dbpath = join(await getDatabasesPath(), dbpath);
|
|
|
|
} else {
|
|
|
|
// Initialize FFI
|
|
|
|
sqfliteFfiInit();
|
|
|
|
// Change the default factory
|
|
|
|
databaseFactory = databaseFactoryFfi;
|
|
|
|
}
|
|
|
|
|
|
|
|
_db = await openDatabase(
|
|
|
|
// Set the path to the database. Note: Using the `join` function from the
|
|
|
|
// `path` package is best practice to ensure the path is correctly
|
|
|
|
// constructed for each platform.
|
2022-08-29 15:16:51 +00:00
|
|
|
dbpath,
|
2022-08-28 20:51:12 +00:00
|
|
|
onCreate: (db, version) {
|
|
|
|
// Run the CREATE TABLE statement on the database.
|
|
|
|
return db.execute(
|
|
|
|
'CREATE TABLE previews(id INTEGER PRIMARY KEY, thumbnail BLOB)',
|
|
|
|
);
|
|
|
|
},
|
|
|
|
// Set the version. This executes the onCreate function and provides a
|
|
|
|
// path to perform database upgrades and downgrades.
|
|
|
|
version: 1,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-08-29 15:16:51 +00:00
|
|
|
/// 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 int cnt = (await Db().db().rawQuery("pragma page_count;"))[0]
|
2022-08-29 15:20:35 +00:00
|
|
|
["page_count"] as int;
|
2022-08-29 15:16:51 +00:00
|
|
|
final int pagesize =
|
2022-08-29 15:20:35 +00:00
|
|
|
(await Db().db().rawQuery("pragma page_size;"))[0]["page_size"] as int;
|
2022-08-29 15:16:51 +00:00
|
|
|
return cnt * pagesize;
|
|
|
|
}
|
|
|
|
|
2022-08-28 20:51:12 +00:00
|
|
|
Database db() {
|
|
|
|
return _db;
|
|
|
|
}
|
|
|
|
|
|
|
|
static final Db _singleton = Db._internal();
|
|
|
|
|
|
|
|
factory Db() {
|
|
|
|
return _singleton;
|
|
|
|
}
|
|
|
|
|
|
|
|
Db._internal();
|
|
|
|
}
|