2023-06-17 21:50:52 +00:00
|
|
|
import 'dart:async';
|
2023-10-19 21:45:07 +00:00
|
|
|
import 'dart:io';
|
2023-07-20 20:56:00 +00:00
|
|
|
import 'package:flutter/foundation.dart';
|
2023-06-17 21:50:52 +00:00
|
|
|
import 'package:sqflite/sqflite.dart';
|
|
|
|
import 'package:path_provider/path_provider.dart' show MissingPlatformDirectoryException, getApplicationDocumentsDirectory;
|
|
|
|
import 'package:tetra_stats/services/crud_exceptions.dart';
|
|
|
|
import 'package:tetra_stats/services/tetrio_crud.dart';
|
|
|
|
import 'package:path/path.dart' show join;
|
|
|
|
|
|
|
|
const String dbName = "TetraStats.db";
|
|
|
|
|
|
|
|
class DB {
|
|
|
|
Database? _db;
|
|
|
|
Future<void> open() async {
|
|
|
|
if (_db != null) {
|
|
|
|
throw DatabaseAlreadyOpen();
|
|
|
|
}
|
|
|
|
try {
|
2023-07-20 20:56:00 +00:00
|
|
|
String dbPath;
|
|
|
|
if (kIsWeb) {
|
|
|
|
dbPath = dbName;
|
|
|
|
} else {
|
|
|
|
final docsPath = await getApplicationDocumentsDirectory();
|
|
|
|
dbPath = join(docsPath.path, dbName);
|
|
|
|
}
|
2023-06-17 21:50:52 +00:00
|
|
|
final db = await openDatabase(dbPath);
|
|
|
|
_db = db;
|
|
|
|
await db.execute(createTetrioUsersTable);
|
|
|
|
await db.execute(createTetrioUsersToTrack);
|
2023-06-23 18:38:15 +00:00
|
|
|
await db.execute(createTetrioTLRecordsTable);
|
2023-06-17 21:50:52 +00:00
|
|
|
} on MissingPlatformDirectoryException {
|
|
|
|
throw UnableToGetDocuments();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> close() async {
|
|
|
|
final db = _db;
|
|
|
|
if (db == null) {
|
|
|
|
throw DatabaseIsNotOpen();
|
|
|
|
} else {
|
|
|
|
await db.close();
|
|
|
|
_db = null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Database getDatabaseOrThrow() {
|
|
|
|
final db = _db;
|
|
|
|
if (db == null) {
|
|
|
|
throw DatabaseIsNotOpen();
|
|
|
|
} else {
|
|
|
|
return db;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> ensureDbIsOpen() async {
|
|
|
|
try {
|
|
|
|
await open();
|
|
|
|
} on DatabaseAlreadyOpen {
|
|
|
|
// empty
|
|
|
|
}
|
|
|
|
}
|
2023-10-19 21:45:07 +00:00
|
|
|
|
|
|
|
Future<int> compressDB() async{
|
|
|
|
await ensureDbIsOpen();
|
|
|
|
final db = getDatabaseOrThrow();
|
|
|
|
String dbPath;
|
|
|
|
if (kIsWeb) {
|
|
|
|
dbPath = dbName;
|
|
|
|
} else {
|
|
|
|
final docsPath = await getApplicationDocumentsDirectory();
|
|
|
|
dbPath = join(docsPath.path, dbName);
|
|
|
|
}
|
|
|
|
var dbFile = File(dbPath);
|
|
|
|
var dbStats = await dbFile.stat();
|
|
|
|
await db.execute("VACUUM");
|
|
|
|
var newDBStats = await dbFile.stat();
|
|
|
|
return dbStats.size - newDBStats.size;
|
|
|
|
}
|
2023-06-17 21:50:52 +00:00
|
|
|
}
|