cpd/lib/database/todo_db.dart

65 lines
2.0 KiB
Dart

import 'package:sqflite/sqflite.dart';
import 'package:cpd/database/db.dart';
import 'package:cpd/database/habit.dart';
class TodoDB {
final tableName = 'todos';
Future<void> createTable(Database database) async {
await database.execute("""CREATE TABLE IF NOT EXISTS $tableName (
id INTEGER PRIMARY KEY AUTOINCREMENT,
isComplete INTEGER NOT NULL,
title TEXT NOT NULL,
subtitle TEXT
)""");
}
Future<int?> create({required String title, required String subtitle}) async {
final database = await HabitDatabase().database;
return await database?.rawInsert(
'''insert into $tableName (isComplete, title, subtitle)
values (?,?,?)''',
[0 ,title, subtitle ?? '']);
}
Future<List<Habit>?> fetchAll() async {
final database = await HabitDatabase().database;
final todos = await database?.query(tableName);
return todos?.map((todo) => Habit.fromSqfliteDatabase(todo)).toList();
}
Future<Habit> fetchById(int id) async {
final database = await HabitDatabase().database;
final todo = await database?.query(tableName, where: 'id = ?', whereArgs: [id]);
return Habit.fromSqfliteDatabase(todo!.first);
}
Future<int?> update({required int id, String? title, required String? subtitle}) async {
final database = await HabitDatabase().database;
return await database?.update(tableName,{
if (title != null) 'title': title,
if (subtitle != null) 'subtitle': subtitle,
},
where: 'id = ?',
conflictAlgorithm: ConflictAlgorithm.rollback,
whereArgs: [id],
);
}
Future<void> delete(int id) async {
final database = await HabitDatabase().database;
await database?.delete(tableName, where: 'id = ?', whereArgs: [id]);
}
Future<int?>? updateCompletionStatus(int id, bool isCompleted) async {
final database = await HabitDatabase().database;
return await database?.update(tableName,{
'isComplete': isCompleted,
},
where: 'id = ?',
conflictAlgorithm: ConflictAlgorithm.rollback,
whereArgs: [id],
);
}
}