2019-04-24 09:24:05 +00:00
|
|
|
import 'package:comunic/helpers/database/database_contract.dart';
|
|
|
|
import 'package:path/path.dart';
|
|
|
|
import 'package:sqflite/sqflite.dart';
|
|
|
|
|
|
|
|
/// Database Helper
|
|
|
|
///
|
|
|
|
/// Manage the connection to the local SQLite database
|
|
|
|
///
|
|
|
|
/// @author Pierre HUBERT
|
|
|
|
|
|
|
|
abstract class DatabaseHelper {
|
2022-03-10 18:39:57 +00:00
|
|
|
static Database? _db;
|
2019-04-24 09:24:05 +00:00
|
|
|
|
|
|
|
/// Open the database
|
|
|
|
static Future<void> open() async {
|
2022-03-10 18:39:57 +00:00
|
|
|
if (_db != null && _db!.isOpen) return;
|
2019-04-24 09:24:05 +00:00
|
|
|
|
|
|
|
var databasePath = await getDatabasesPath();
|
|
|
|
_db = await openDatabase(
|
|
|
|
join(databasePath, DatabaseContract.DATABASE_FILE_NAME),
|
|
|
|
version: DatabaseContract.DATABASE_VERSION,
|
|
|
|
onUpgrade: _performDatabaseUpdate,
|
|
|
|
onCreate: _initializeDatabase);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Get a database instance
|
2022-03-10 18:39:57 +00:00
|
|
|
static Future<Database?> get() async {
|
2019-04-24 09:24:05 +00:00
|
|
|
await open();
|
|
|
|
return _db;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Perform database update
|
|
|
|
///
|
|
|
|
/// Currently : delete all the database tables and initialize it again
|
|
|
|
static Future<void> _performDatabaseUpdate(
|
|
|
|
Database db, int oldVersion, int newVersion) async {
|
2019-05-04 17:35:03 +00:00
|
|
|
// Drop friends list table
|
2020-04-17 09:53:47 +00:00
|
|
|
await db
|
|
|
|
.execute("DROP TABLE IF EXISTS ${FriendsListTableContract.TABLE_NAME}");
|
2019-05-04 17:35:03 +00:00
|
|
|
|
2019-04-24 12:25:46 +00:00
|
|
|
// Initialize database again
|
2019-04-24 09:24:05 +00:00
|
|
|
await _initializeDatabase(db, newVersion);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Initialize the database
|
|
|
|
static Future<void> _initializeDatabase(Database db, int version) async {
|
2019-05-04 17:35:03 +00:00
|
|
|
// Friends list table
|
|
|
|
await db.execute("CREATE TABLE ${FriendsListTableContract.TABLE_NAME} ("
|
|
|
|
"${FriendsListTableContract.C_ID} INTEGER PRIMARY KEY, "
|
|
|
|
"${FriendsListTableContract.C_ACCEPTED} INTEGER, "
|
|
|
|
"${FriendsListTableContract.C_LAST_ACTIVE} INTEGER, "
|
|
|
|
"${FriendsListTableContract.C_FOLLOWING} INTEGER, "
|
|
|
|
"${FriendsListTableContract.C_CAN_POST_TEXTS} INTEGER"
|
|
|
|
")");
|
2019-04-24 09:24:05 +00:00
|
|
|
}
|
|
|
|
}
|