Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor/database #1220

Merged
merged 28 commits into from
Jul 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
96cb235
Made app_database class abstract and implemented logic to encapsulate…
vitormpp Mar 27, 2024
1151cb7
Implemented logic to encapsulate persistent logic in all database cla…
vitormpp Mar 27, 2024
b9ad0d3
Updated providers according to previous changes in database classes
vitormpp Mar 27, 2024
8185590
Updated providers so that they save data to database only if session …
vitormpp Mar 27, 2024
67929ce
Made small changes in providers to encapsulate persistent session logic
vitormpp Apr 3, 2024
be9d919
fix: app_user_database
vitormpp Apr 3, 2024
1cb9a81
Fixed error in app_database
vitormpp May 29, 2024
728982d
Fixed lint error
vitormpp May 29, 2024
0428a37
fix: app user database
vitormpp Jun 5, 2024
522e133
fix: lint error
vitormpp Jun 5, 2024
aab6a96
Merge branch 'develop' into refactor/data-base
vitormpp Jun 5, 2024
3111a62
Small fix to providers
vitormpp Jul 3, 2024
193736e
Merge branch 'refactor/data-base' of github.com:NIAEFEUP/uni into ref…
vitormpp Jul 3, 2024
ea07c32
Made app_database class abstract and implemented logic to encapsulate…
vitormpp Mar 27, 2024
380ee85
Implemented logic to encapsulate persistent logic in all database cla…
vitormpp Mar 27, 2024
6ddbc01
Updated providers according to previous changes in database classes
vitormpp Mar 27, 2024
08e5c52
Updated providers so that they save data to database only if session …
vitormpp Mar 27, 2024
21c8f10
Made small changes in providers to encapsulate persistent session logic
vitormpp Apr 3, 2024
21c513b
fix: app_user_database
vitormpp Apr 3, 2024
9cb68ba
Fixed error in app_database
vitormpp May 29, 2024
7290b6f
Fixed lint error
vitormpp May 29, 2024
c6b4cc7
fix: app user database
vitormpp Jun 5, 2024
fbe3193
fix: lint error
vitormpp Jun 5, 2024
82d6052
Small fix to providers
vitormpp Jul 3, 2024
fea1173
fix lint errors
vitormpp Jul 3, 2024
9a50314
Merge branch 'refactor/data-base' of github.com:NIAEFEUP/uni into ref…
vitormpp Jul 3, 2024
9576016
fix: tests
vitormpp Jul 3, 2024
9cb9871
Merge branch 'develop' into refactor/data-base
DGoiana Jul 4, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,15 @@ import 'package:uni/model/entities/bus_stop.dart';
/// This database stores information about the bus stops that the user
/// wants to keep track of. It also stores information about
/// which ones are the user's favorite stops.
class AppBusStopDatabase extends AppDatabase {
class AppBusStopDatabase extends AppDatabase<Map<String, BusStopData>> {
AppBusStopDatabase()
: super('busstops.db', [
'CREATE TABLE busstops(stopCode TEXT, busCode TEXT)',
'CREATE TABLE favoritestops(stopCode TEXT, favorited TEXT)',
]);
: super(
'busstops.db',
[
'CREATE TABLE busstops(stopCode TEXT, busCode TEXT)',
'CREATE TABLE favoritestops(stopCode TEXT, favorited TEXT)',
],
);

/// Returns a map containing all the data stored in this database.
///
Expand Down Expand Up @@ -103,9 +106,10 @@ class AppBusStopDatabase extends AppDatabase {
}

/// Replaces all the bus stops in this database with entries
/// from [stops].
Future<void> setBusStops(Map<String, BusStopData> stops) async {
/// from [data].
@override
Future<void> saveToDatabase(Map<String, BusStopData> data) async {
await deleteBusStops();
await _insertBusStops(stops);
await _insertBusStops(data);
}
}
Original file line number Diff line number Diff line change
@@ -1,25 +1,18 @@
import 'package:uni/controller/local_storage/database/app_database.dart';
import 'package:uni/model/entities/calendar_event.dart';

class CalendarDatabase extends AppDatabase {
class CalendarDatabase extends AppDatabase<List<CalendarEvent>> {
CalendarDatabase()
: super('calendar.bd', [
'''
: super(
'calendar.bd',
[
'''
CREATE TABLE CALENDAR(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
date TEXT)'''
]);

Future<void> saveCalendar(List<CalendarEvent> calendar) async {
final db = await getDatabase();
await db.transaction((txn) async {
await txn.delete('CALENDAR');
for (final event in calendar) {
await txn.insert('CALENDAR', event.toMap());
}
});
}
],
);

// Returns a list with all calendar events stored in the database
Future<List<CalendarEvent>> calendar() async {
Expand All @@ -34,4 +27,15 @@ class CalendarDatabase extends AppDatabase {
);
});
}

@override
Future<void> saveToDatabase(List<CalendarEvent> data) async {
final db = await getDatabase();
await db.transaction((txn) async {
await txn.delete('CALENDAR');
for (final event in data) {
await txn.insert('CALENDAR', event.toMap());
}
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,18 @@ import 'package:sqflite/sqflite.dart';
import 'package:uni/controller/local_storage/database/app_database.dart';
import 'package:uni/model/entities/course_units/course_unit.dart';

class AppCourseUnitsDatabase extends AppDatabase {
AppCourseUnitsDatabase() : super('course_units.db', [createScript]);
class AppCourseUnitsDatabase extends AppDatabase<List<CourseUnit>> {
AppCourseUnitsDatabase()
: super(
'course_units.db',
[createScript],
);
static const String createScript =
'''CREATE TABLE course_units(id INTEGER, code TEXT, abbreviation TEXT , '''
'''name TEXT, curricularYear INTEGER, occurrId INTEGER, semesterCode TEXT, '''
'''semesterName TEXT, type TEXT, status TEXT, grade TEXT, ectsGrade TEXT, '''
'''result TEXT, ects REAL, schoolYear TEXT)''';

Future<void> saveNewCourseUnits(List<CourseUnit> courseUnits) async {
await deleteCourseUnits();
await _insertCourseUnits(courseUnits);
}

Future<List<CourseUnit>> courseUnits() async {
final db = await getDatabase();
final List<Map<String, dynamic>> maps = await db.query('course_units');
Expand Down Expand Up @@ -56,4 +55,10 @@ class AppCourseUnitsDatabase extends AppDatabase {
final db = await getDatabase();
await db.delete('course_units');
}

@override
Future<void> saveToDatabase(List<CourseUnit> data) async {
await deleteCourseUnits();
await _insertCourseUnits(data);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,19 @@ import 'package:uni/model/entities/course.dart';
///
/// This database stores information about the user's courses.
/// See the [Course] class to see what data is stored in this database.
class AppCoursesDatabase extends AppDatabase {
class AppCoursesDatabase extends AppDatabase<List<Course>> {
AppCoursesDatabase()
: super('courses.db', [createScript], onUpgrade: migrate, version: 3);
: super(
'courses.db',
[createScript],
onUpgrade: migrate,
version: 3,
);
static const String createScript =
'''CREATE TABLE courses(id INTEGER, fest_id INTEGER, name TEXT, '''
'''abbreviation TEXT, currYear TEXT, firstEnrollment INTEGER, state TEXT, '''
'''faculty TEXT, currentAverage REAL, finishedEcts REAL)''';

/// Replaces all of the data in this database with the data from [courses].
Future<void> saveNewCourses(List<Course> courses) async {
await deleteCourses();
await _insertCourses(courses);
}

/// Returns a list containing all of the courses stored in this database.
Future<List<Course>> courses() async {
final db = await getDatabase();
Expand Down Expand Up @@ -77,4 +76,11 @@ class AppCoursesDatabase extends AppDatabase {
..execute(createScript);
await batch.commit();
}

/// Replaces all of the data in this database with the data from [data].
@override
Future<void> saveToDatabase(List<Course> data) async {
await deleteCourses();
await _insertCourses(data);
}
}
31 changes: 27 additions & 4 deletions uni/lib/controller/local_storage/database/app_database.dart
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import 'dart:async';

import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:synchronized/synchronized.dart';
import 'package:uni/controller/local_storage/preferences_controller.dart';

/// Manages a generic database.
///
/// This class is the foundation for all other database managers.
class AppDatabase {
AppDatabase(this.name, this.commands, {this.onUpgrade, this.version = 1});
abstract class AppDatabase<T> {
AppDatabase(
this.name,
this.commands, {
this.onUpgrade,
this.version = 1,
});

/// An instance of this database.
Database? _db;
Expand All @@ -20,6 +24,9 @@ class AppDatabase {
/// A list of commands to be executed on database creation.
List<String> commands;

/// Whether the session is persistent or not.
bool? _persistentSession;

/// The lock timeout for database operations.
static const Duration lockTimeout = Duration(seconds: 5);

Expand All @@ -32,12 +39,28 @@ class AppDatabase {
/// The version of this database.
final int version;

/// Getter to determine if the session is persistent.
Future<bool> get persistentSession async {
_persistentSession ??=
await PreferencesController.getPersistentUserInfo() != null;
return _persistentSession!;
bdmendes marked this conversation as resolved.
Show resolved Hide resolved
}

/// Returns an instance of this database.
Future<Database> getDatabase() async {
_db ??= await initializeDatabase();
return _db!;
}

Future<void> saveToDatabase(T data);
vitormpp marked this conversation as resolved.
Show resolved Hide resolved

/// Calls saveToDatabase if the session is persistent
Future<void> saveIfPersistentSession(T data) async {
if (await persistentSession) {
await saveToDatabase(data);
}
vitormpp marked this conversation as resolved.
Show resolved Hide resolved
}

/// Inserts [values] into the corresponding [table] in this database.
Future<void> insertInDatabase(
String table,
Expand Down
22 changes: 14 additions & 8 deletions uni/lib/controller/local_storage/database/app_exams_database.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,19 @@ import 'package:uni/model/entities/exam.dart';
///
/// This database stores information about the user's exams.
/// See the [Exam] class to see what data is stored in this database.
class AppExamsDatabase extends AppDatabase {
class AppExamsDatabase extends AppDatabase<List<Exam>> {
AppExamsDatabase()
: super('exams.db', [_createScript], onUpgrade: migrate, version: 5);
: super(
'exams.db',
[_createScript],
onUpgrade: migrate,
version: 5,
);

static const _createScript = '''
CREATE TABLE exams(id TEXT, subject TEXT, begin TEXT, end TEXT,
rooms TEXT, examType TEXT, faculty TEXT, PRIMARY KEY (id,faculty)) ''';

/// Replaces all of the data in this database with [exams].
Future<void> saveNewExams(List<Exam> exams) async {
await deleteExams();
await _insertExams(exams);
}

/// Returns a list containing all of the exams stored in this database.
Future<List<Exam>> exams() async {
final db = await getDatabase();
Expand Down Expand Up @@ -70,4 +69,11 @@ CREATE TABLE exams(id TEXT, subject TEXT, begin TEXT, end TEXT,
..execute(_createScript);
await batch.commit();
}

/// Replaces all of the data in this database with [data].
@override
Future<void> saveToDatabase(List<Exam> data) async {
await deleteExams();
await _insertExams(data);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,12 @@ import 'package:uni/controller/local_storage/database/app_database.dart';
///
/// This database stores information about when the app last fetched and updated
/// the user's data.
class AppLastUserInfoUpdateDatabase extends AppDatabase {
class AppLastUserInfoUpdateDatabase extends AppDatabase<DateTime> {
AppLastUserInfoUpdateDatabase()
: super('last_update.db', ['CREATE TABLE last_update(lastUpdate DATE)']);

/// Replaces the timestamp in this database with [timestamp].
Future<void> insertNewTimeStamp(DateTime timestamp) async {
await deleteLastUpdate();
await _insertTimeStamp(timestamp);
}
: super(
'last_update.db',
['CREATE TABLE last_update(lastUpdate DATE)'],
);

/// Deletes all of the data from this database.
Future<void> deleteLastUpdate() async {
Expand Down Expand Up @@ -41,4 +38,11 @@ class AppLastUserInfoUpdateDatabase extends AppDatabase {
}
return DateTime.now();
}

/// Replaces the timestamp in this database with [data].
@override
Future<void> saveToDatabase(DateTime data) async {
await deleteLastUpdate();
await _insertTimeStamp(data);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import 'package:uni/model/entities/lecture.dart';
///
/// This database stores information about the user's lectures.
/// See the [Lecture] class to see what data is stored in this database.
class AppLecturesDatabase extends AppDatabase {
class AppLecturesDatabase extends AppDatabase<List<Lecture>> {
AppLecturesDatabase()
: super(
'lectures.db',
Expand All @@ -22,12 +22,6 @@ class AppLecturesDatabase extends AppDatabase {
CREATE TABLE lectures(subject TEXT, typeClass TEXT,
startDateTime TEXT, blocks INTEGER, room TEXT, teacher TEXT, classNumber TEXT, occurrId INTEGER)''';

/// Replaces all of the data in this database with [lectures].
Future<void> saveNewLectures(List<Lecture> lectures) async {
await deleteLectures();
await _insertLectures(lectures);
}

/// Returns a list containing all of the lectures stored in this database.
Future<List<Lecture>> lectures() async {
final db = await getDatabase();
Expand Down Expand Up @@ -82,4 +76,11 @@ CREATE TABLE lectures(subject TEXT, typeClass TEXT,
..execute(createScript);
await batch.commit();
}

/// Replaces all of the data in this database with [lectures].
@override
Future<void> saveToDatabase(List<Lecture> data) async {
await deleteLectures();
await _insertLectures(data);
}
}
Original file line number Diff line number Diff line change
@@ -1,28 +1,21 @@
import 'package:uni/controller/local_storage/database/app_database.dart';
import 'package:uni/model/entities/library_occupation.dart';

class LibraryOccupationDatabase extends AppDatabase {
class LibraryOccupationDatabase extends AppDatabase<LibraryOccupation> {
LibraryOccupationDatabase()
: super('occupation.db', [
'''
CREATE TABLE FLOOR_OCCUPATION(
id INTEGER PRIMARY KEY AUTOINCREMENT,
number INT,
occupation INT,
capacity INT
)
'''
]);

Future<void> saveOccupation(LibraryOccupation occupation) async {
final db = await getDatabase();
await db.transaction((txn) async {
await txn.delete('FLOOR_OCCUPATION');
for (final floor in occupation.floors) {
await txn.insert('FLOOR_OCCUPATION', floor.toMap());
}
});
}
: super(
'occupation.db',
[
'''
CREATE TABLE FLOOR_OCCUPATION(
id INTEGER PRIMARY KEY AUTOINCREMENT,
number INT,
occupation INT,
capacity INT
)
'''
],
);

Future<LibraryOccupation> occupation() async {
final db = await getDatabase();
Expand All @@ -43,4 +36,15 @@ CREATE TABLE FLOOR_OCCUPATION(

return occupation;
}

@override
Future<void> saveToDatabase(LibraryOccupation data) async {
final db = await getDatabase();
await db.transaction((txn) async {
await txn.delete('FLOOR_OCCUPATION');
for (final floor in data.floors) {
await txn.insert('FLOOR_OCCUPATION', floor.toMap());
}
});
}
}
Loading